def check_version(editor, p_settings, upgrade_callback):
    update_available = False
    version, version_limits = read_versions()

    if version is not None and version_limits is not None:
        # True if versions are okay
        ignore_key = "%s:%s" % (version, version_limits["max"])
        if not version_compare(version, version_limits["min"]):
            ignore_versions = str(p_settings.get("ignore_version_update", ""))
            if not ignore_key == ignore_versions:
                if sublime.ok_cancel_dialog(MSGS["upgrade"] % version_limits["max"], "Update"):
                    update_binary(upgrade_callback)
                    update_available = True
                elif sublime.ok_cancel_dialog(MSGS["ignore_critical"] % (version, version_limits["min"]), "Ignore"):
                    p_settings.set("ignore_version_update", ignore_key)
                    sublime.save_settings(PLUGIN_SETTINGS)

        elif not version_compare(version, version_limits["max"]):
            if sublime.ok_cancel_dialog(MSGS["upgrade"] % version_limits["max"], "Update"):
                update_binary(upgrade_callback)
                update_available = True
            elif sublime.ok_cancel_dialog(MSGS["ignore_critical"], "Ignore"):
                p_settings.set("ignore_version_update", ignore_key)
                sublime.save_settings(PLUGIN_SETTINGS)
    else:
        sublime.error_message(MSGS["version"])
    return update_available
Example #2
0
	def Is_save(self):
		'''
		@ 函数名:Is_save		 --> 作者:Dandy.Mu
		@ 函数说明:检测当前文件是否已经保存
		@ 谱写日期:2013-12-17 10:37:59
		'''

		self.FILE = None

		# 当前文件的对象
		self.FILE = self.view.file_name()

		# 检测文件是否存在,也就是说文件是否已经创建,语法检测和运行的时候需要用到
		if not os.path.exists(self.FILE):
			if sublime.ok_cancel_dialog('搞不了, 是不是还没有保存文件啊?\n现在保存不?'.decode('utf-8')):
				self.view.run_command('save')
			else:
				return sublime.status_message('你吖不保存,偶搞不了!'.decode('utf-8'))

		# 检测当前文件是否已经保存
		if self.view.is_dirty():
			if sublime.ok_cancel_dialog("当前文件未保存, 是否现在保存当前文件?.".decode('utf-8')):
				self.view.run_command('save')
			else:
				return sublime.status_message('文件未保存取消检测!'.decode('utf-8'))

		# 检测扩展名是否为PHP
		if not self.FILE[-3:] == 'php':
			if not sublime.ok_cancel_dialog("当前文件可能不是PHP文件, 是否要继续执行?".decode('utf-8')):
				return sublime.status_message('取消非PHP文件的语法检测!'.decode('utf-8'))

		return self.FILE;
		pass
Example #3
0
    def run(self):
        while 1:
            self.recording(self.workingMins, updateWorkingTimeStatus)
            self.pomodoroCounter = self.pomodoroCounter + 1

            if settings().get("event_logging"):
                sublime.active_window().show_input_panel("What did you just do?:", "", self.add_to_log, None, self.on_cancel)
            
            if self.stopped(): 
                #sublime.error_message('Pomodoro Cancelled')
                break
                
            while self.wait:
                time.sleep(1)

            self.wait = True
            breakType =  self.pomodoroCounter % (self.numberPomodoro)
            print(breakType)
            if breakType == 0:
                
                rest = sublime.ok_cancel_dialog('Time for a long break.', 'OK')
            else:
                rest = sublime.ok_cancel_dialog('Time for a short break.', 'OK')
            if rest:
                if breakType == 0:
                    self.recording(self.longBreakMins, updateRestingTimeStatus)
                else:
                    self.recording(self.shortBreakMins, updateRestingTimeStatus)
                work = sublime.ok_cancel_dialog("Break over. Start next pomodoro?", 'OK')
            if not work:
                self.stop()

        time.sleep(2)
        self.stop()
Example #4
0
    def run(self):
        repo = self.get_repo()
        if not repo:
            return

        branch = self.get_current_branch(repo)
        if not branch:
            return sublime.error_message("You really shouldn't push a detached head")

        remotes = self.get_remotes(repo)
        if not remotes:
            if sublime.ok_cancel_dialog(NO_REMOTES, 'Add Remote'):
                self.window.run_command('git_remote_add')
                return

        branch_remote, branch_merge = self.get_branch_upstream(repo, branch)
        if not branch_remote or not branch_merge:
            if sublime.ok_cancel_dialog(NO_TRACKING, 'Yes'):
                self.window.run_command('git_pull_current_branch')
            return

        self.panel = self.window.get_output_panel('git-pull')
        self.panel_shown = False

        thread = self.git_async(['pull', '-v'], cwd=repo, on_data=self.on_data)
        runner = StatusSpinner(thread, "Pulling from %s" % (branch_remote))
        runner.start()
Example #5
0
    def run(self):
        # For Windows
        if is_windows():
            if os.path.exists(get_location()):
                runWinBeyondCompare()
                return
            else:
                sublime.error_message('Could not find Beyond Compare. Please set the path to your tool in BeyondCompare.sublime-settings.')
                return

        # For OSX
        if os.path.exists(get_location()):
            runMacBeyondCompare()

        else:
            commandLinePrompt = sublime.ok_cancel_dialog('Could not find bcompare.\nPlease install the command line tools.', 'Do it now!')
            if commandLinePrompt:
                new = 2  # open in a new tab, if possible
                url = "http://www.scootersoftware.com/support.php?zz=kb_OSXInstallCLT"
                webbrowser.open(url, new=new)
                bCompareInstalled = sublime.ok_cancel_dialog('Once you have installed the command line tools, click the ok button to continue')
                if bCompareInstalled:
                    if os.path.exists("/usr/local/bin/bcompare"):
                        runMacBeyondCompare()

                    else:
                        sublime.error_message('Still could not find bcompare. \nPlease make sure it exists at:\n/usr/local/bin/bcompare\nand try again')

                else:
                    sublime.error_message('Please try again after you have command line tools installed.')
            else:
                sublime.error_message('Please try again after you have command line tools installed.')
Example #6
0
    def on_enter_directory(self, path):
        self.suggested_git_root = path
        if self.suggested_git_root and os.path.exists(os.path.join(self.suggested_git_root, ".git")):
            sublime.ok_cancel_dialog(RECLONE_CANT_BE_DONE)
            return

        sublime.set_timeout_async(self.do_clone, 0)
def handle_result(operation, process_id, printer, result, thread):
    #print(thread.process_id)
    #print(thread.params)
    process_region = printer.panel.find(process_id,0)
    status_region = printer.panel.find('Result:',process_region.begin())

    try:
        result = json.loads(result)
        if operation == 'compile' and 'actions' in result and util.to_bool(result['success']) == False:
            diff_merge_settings = config.settings.get('mm_diff_server_conflicts', False)
            if diff_merge_settings:
                if sublime.ok_cancel_dialog(result["body"], result["actions"][0].title()):
                    printer.panel.run_command('write_operation_status', {"text": " Diffing with server", 'region': [status_region.end(), status_region.end()+10] })
                    th = MavensMateDiffThread(thread.window, thread.view, result['tmp_file_path'])
                    th.start()
                    
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
            else:
                if sublime.ok_cancel_dialog(result["body"], "Overwrite Server Copy"):
                    printer.panel.run_command('write_operation_status', {"text": " Overwriting server copy", 'region': [status_region.end(), status_region.end()+10] })
                    thread.params['action'] = 'overwrite'
                    sublime.set_timeout(lambda: call('compile', params=thread.params), 100)   
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
   
        else:
            print_result_message(operation, process_id, status_region, result, printer, thread) 
            if operation == 'new_metadata' and 'success' in result and util.to_bool(result['success']) == True:
                if 'messages' in result:
                    if type(result['messages']) is not list:
                        result['messages'] = [result['messages']]
                    for m in result['messages']:
                        if 'package.xml' not in m['fileName']:
                            file_name = m['fileName']
                            location = util.mm_project_directory() + "/" + file_name.replace('unpackaged/', 'src/')
                            sublime.active_window().open_file(location)
                            break
            if 'success' in result and util.to_bool(result['success']) == True:
                if printer != None and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                    printer.hide()  
            elif 'State' in result and result['State'] == 'Completed' and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                #tooling api
                if printer != None:
                    printer.hide()
            if operation == 'refresh':            
                sublime.set_timeout(lambda: sublime.active_window().active_view().run_command('revert'), 200)
                util.clear_marked_line_numbers()
    except AttributeError:   
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
    except Exception:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
Example #8
0
    def run(self):
        while 1:
            if self.stopped():
                stopRecording()
                time.sleep(2)
                continue

            self.recording(self.workingMins, updateWorkingTimeStatus)

            if self.stopped():
                stopRecording()
                time.sleep(2)
                continue

            rest = sublime.ok_cancel_dialog('Hey, you are working too hard, take a rest.', 'OK')
            if rest:
                self.recording(self.restingMins, updateRestingTimeStatus)
                if self.stopped():
                    stopRecording()
                    time.sleep(2)
                    continue
                work = sublime.ok_cancel_dialog("Come on, let's continue.", 'OK')
                if not work:
                    self.stop()
            time.sleep(2)
Example #9
0
 def handle_unknown_error(err):
     print(err)
     msg = "An unhandled error was encountered while prettifying. See the console output for more information. Do you wish to file a bug?"
     if ok_cancel_dialog(msg):
         msg = "Please include detailed information in your bug report."
         if ok_cancel_dialog(msg):
             file_bug()
     return None
 def onselect_003(self):
     if self.type_db != 'M':
         sublime.message_dialog(self.MESSAGE_MYSQL)
         return
     sublime.ok_cancel_dialog(
         'Current database on remote server will be destroyed. \
         Are you sure?', 'Continue')
     Tools.show_input_panel(
         'Input confirmation password', '', self.oninput_003, None, None)
Example #11
0
    def on_input(self, input):
        # Create component to local according to user input
        if self.template_attr["extension"] == ".trigger":
            if not re.match('^[a-zA-Z]+\\w+,[_a-zA-Z]+\\w+$', input):
                message = 'Invalid format, do you want to try again?'
                if not sublime.ok_cancel_dialog(message): return
                self.window.show_input_panel("Follow [Name<,sobject for trigger>]", 
                    "", self.on_input, None, None)
                return
            name, sobject = [ele.strip() for ele in input.split(",")]
        else:
            if not re.match('^[a-zA-Z]+\\w+$', input):
                message = 'Invalid format, are you want to input again?'
                if not sublime.ok_cancel_dialog(message): return
                self.window.show_input_panel("Follow [Name<,sobject for trigger>]", 
                    "", self.on_input, None, None)
                return
            name = input
        
        extension = self.template_attr["extension"]
        body = self.template_attr["body"]
        if extension == ".trigger":
            body = body % (name, sobject)
        elif extension == ".cls":
            body = body.replace("class_name", name)

        settings = context.get_toolingapi_settings()
        component_type = settings[extension]
        component_outputdir = settings[component_type]["outputdir"]
        if not os.path.exists(component_outputdir):
            os.makedirs(component_outputdir)
            settings = context.get_toolingapi_settings()
            context.add_project_to_workspace(settings["workspace"])

        file_name = "%s/%s" % (component_outputdir, name + extension)
        if os.path.isfile(file_name):
            self.window.open_file(file_name)
            sublime.error_message(name + " is already exist")
            return

        with open(file_name, "w") as fp:
            fp.write(body)

        # Compose data
        data = {
            "name": name,
            settings[component_type]["body"]: body,
        }
        if component_type == "ApexClass":
            data["IsValid"] = True
        elif component_type == "ApexTrigger":
            data["TableEnumOrId"] = sobject
        elif component_type in ["ApexPage", "ApexComponent"]:
            data["MasterLabel"] = name

        processor.handle_create_component(data, name, component_type, file_name)
Example #12
0
def safe_open(filename, mode, *args, **kwargs):
    try:
        with open(filename, mode, *args, **kwargs) as file:
            yield file
    except PermissionError as e:
        sublime.ok_cancel_dialog("GitSavvy could not access file: \n{}".format(e))
        raise e
    except OSError as e:
        sublime.ok_cancel_dialog("GitSavvy encountered an OS error: \n{}".format(e))
        raise e
 def _user_permission_dialog():
     message = "Mousemap already exists. Do you want to overwrite it?"
     ok = sublime.ok_cancel_dialog(message, "Overwrite")
     if ok:
         result = _OVERWRITE
     else:
         message = "Do you want me to change it?"
         ok = sublime.ok_cancel_dialog(message, "Change existing mousemap")
         result = _CHANGE if ok else _CANCEL
     return result
Example #14
0
def notify_user(message):
    """
    Open a dialog for the user to inform them of a user interaction that is
    part of the test suite

    :param message:
        A unicode string of the message to present to the user
    """

    sublime.ok_cancel_dialog('Test Suite for Golang Build\n\n' + message, 'Ok')
def load_launch(env):
    if not os.path.exists(env.session_file) or not os.path.getsize(env.session_file):
        message = "Launch configuration does not exist. "
        message += "Sublime will now create a configuration file for you. Do you wish to proceed?"
        if sublime.ok_cancel_dialog(message):
            env.save_session()  # to pre-populate the config, so that the user has easier time filling it in
            env.w.run_command("ensime_show_session")
        return None

    session = env.load_session()
    if not session:
        message = "Launch configuration for the Ensime project could not be loaded. "
        message += "Maybe the config is not accessible, but most likely it's simply not a valid JSON. "
        message += "\n\n"
        message += "Sublime will now open the configuration file for you to fix. "
        message += "If you don't know how to fix the config, delete it and Sublime will recreate it from scratch. "
        message += "Do you wish to proceed?"
        if sublime.ok_cancel_dialog(message):
            env.w.run_command("ensime_show_session")
        return None

    launch = session.launch
    if not launch:
        message = "Your current " + session.launch_name + " is not present. "
        message += "\n\n"
        message += "This error happened because the \"current_launch_config\" field of the config "
        if session.launch_key:
            config_status = "set to \"" + session.launch_key + "\""
        else:
            config_status = "set to an empty string"
        message += "(which is currently " + config_status + ") "
        message += "doesn't correspond to any entries in the \"launch_configs\" field of the launch configuration."
        message += "\n\n"
        message += "Sublime will now open the configuration file for you to fix. Do you wish to proceed?"
        if sublime.ok_cancel_dialog(message):
            env.w.run_command("ensime_show_session")
        return None

    if not launch.is_valid():
        message = "Your current " + session.launch_name + " is incorrect. "
        message += "\n\n"
        if session.launch_key:
            launch_description = "the entry named \"" + session.launch_key + "\""
        else:
            launch_description = "the default unnamed entry"
        message += "This error happened because " + launch_description + \
                   " in the \"launch_configs\" field of the launch configuration "
        message += "has neither the \"main_class\", nor the \"remote_address\" attribute set."
        message += "\n\n"
        message += "Sublime will now open the configuration file for you to fix. Do you wish to proceed?"
        if sublime.ok_cancel_dialog(message):
            env.w.run_command("ensime_show_session")
        return None

    return launch
Example #16
0
    def handle_output_diagnostics(output):
        if get_pref("print_diagnostics"):
            print(output)

        file_parse_error = get_diagnostics_parse_fail(output)
        if file_parse_error:
            msg = "Ignoring malformed config file: " + file_parse_error.group(1)
            if ok_cancel_dialog(msg):
                msg = "Please fix the syntax errors in your config file and try again. See the console output for more information. Do you wish to file a bug instead?"
                if ok_cancel_dialog(msg):
                    file_bug()
Example #17
0
 def run(self):
     while 1:
         self.recording(self.workingMins, updateWorkingTimeStatus)
         rest = sublime.ok_cancel_dialog('Hey, you are working too hard, take a rest.', 'OK')
         if rest:
             self.recording(self.restingMins, updateRestingTimeStatus)
             work = sublime.ok_cancel_dialog("Come on, let's continue.", 'OK')
             if not work:
                 break
         else:
             break
     self.stop()
		def on_done(i):
			if i == 0:
				self.show_quick_panel()
			elif i == 1 and item["installed"]:
				if sublime.ok_cancel_dialog("Remove \"%s\"" % item["name"], "Remove"):
					self.window.run_command("tlmgr_simple", {"cmd": ["remove", item["name"]], "sudo": True})
			elif i == 1 and not item["installed"]:
				if sublime.ok_cancel_dialog("Install \"%s\"" % item["name"], "Install"):
					self.window.run_command("tlmgr_simple", {"cmd": ["install", item["name"]], "sudo": True})
			elif i == 2:
				if sublime.ok_cancel_dialog("Update \"%s\"" % item["name"], "Update"):
					self.window.run_command("tlmgr_simple", {"cmd": ["update", item["name"]], "sudo": True})
			elif i == 3:
				if sublime.ok_cancel_dialog("Force Update \"%s\"" % item["name"], "Update"):
					self.window.run_command("tlmgr_simple", {"cmd": ["update", "--force", item["name"]], "sudo": True})
Example #19
0
	def goruncmd(self, runCmd):
		proc = subprocess.Popen(runCmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
		sublime.ok_cancel_dialog("Services is running, you can look log at console.", "I know")
		try:
			while True:
				ln = proc.stdout.readline()
				print(">>>#: ", ln)
				if not ln:
					break
		except Exception:
			print("ex >>>")

		proc.stdout.close()
		proc.wait()
		proc = None
Example #20
0
    def on_input(self, lighting_name):
        # Create component to local according to user input
        if not re.match('^[a-zA-Z]+\\w+$', lighting_name):
            message = 'Invalid format, do you want to try again?'
            if not sublime.ok_cancel_dialog(message): return
            self.window.show_input_panel("Please Input %s Name: " % self._type, 
                "", self.on_input, None, None)
            return

        # Get settings
        settings = context.get_settings()
        workspace = settings["workspace"]

        # Get template attribute
        templates = util.load_templates()
        template = templates.get("Aura").get(self._type)        
        with open(os.path.join(workspace, ".templates", template["directory"])) as fp:
            body = fp.read()

        # Build dir for new lighting component
        component_dir = os.path.join(workspace, "src", "aura", lighting_name)
        if not os.path.exists(component_dir):
            os.makedirs(component_dir)
        else:
            message = "%s is already exist, do you want to try again?" % lighting_name
            if not sublime.ok_cancel_dialog(message, "Try Again?"): return
            self.window.show_input_panel("Please Input Lighting Name: ", 
                "", self.on_input, None, None)
            return
        
        lihghting_file = os.path.join(component_dir, lighting_name+template["extension"])

        # Create Aura lighting file
        with open(lihghting_file, "w") as fp:
            fp.write(body)

        # If created succeed, just open it and refresh project
        window = sublime.active_window()
        window.open_file(lihghting_file)
        window.run_command("refresh_folder_list")

        # Deploy Aura to server
        self.window.run_command("deploy_lighting_to_server", {
            "dirs": [component_dir],
            "switch_project": False,
            "element": self._type,
            "update_meta": True
        })
		def on_done(index):
			if index == -1: return
			select = folder[index]
			# print(select)
			exist = []
			overwrite = 'none' # none all file system
			for file in workflowFiles:
				result = os.path.exists(os.path.abspath(os.path.join(select, file)))
				exist.append(result)

			if os.path.exists(self.window.project_file_name()):
				with open (self.window.project_file_name(), 'r+', encoding='utf8') as project:
					projectData = project.readlines()
					exist.append('\t"build_systems":\n' in projectData)
			else:
				sublime.message_dialog("請先建立project\nProject -> Save Project As...")
			
			if True in exist:
				while exist.count(True) == len(exist):
					if sublime.yes_no_cancel_dialog(
						'build tool 已建立\n是否要更新為最新版本', '全部更新', '指定更新'
						) == sublime.DIALOG_NO:
						if sublime.yes_no_cancel_dialog(
							'請選擇要更新的項目', '更新 task 及 package.json', '更新 build system'
							) == sublime.DIALOG_YES:
							overwrite = 'file'
						elif sublime.DIALOG_NO:
							overwrite = 'system'
						elif sublime.DIALOG_CANCEL:
							return None
					elif sublime.DIALOG_YES:
						overwrite = 'all'
					elif sublime.DIALOG_CANCEL:
						 return None
					break
				while overwrite == 'none' and exist.index(True) < len(exist) - 1:
					if not sublime.ok_cancel_dialog('task 和 package 已建立\n是否需要更新為最新版本', '更新'):
						overwrite = 'system'
					else:
						overwrite = 'file'
					break
				while overwrite == 'none' and exist.index(True) == len(exist) - 1:
					if not sublime.ok_cancel_dialog('build system 已建立\n是否需要更新為最新版本', '更新'):
						overwrite = 'file'
					break	

			# print('overwrite '+ overwrite)
			copyFiles(select, copied, overwrite)
Example #22
0
 def run(self, dirs):
     if sublime.ok_cancel_dialog("Delete Folder?", "Delete"):
         try:
             for d in dirs:
                 send2trash.send2trash(d)
         except:
             sublime.status_message("Unable to delete folder")
Example #23
0
    def run(self, edit):
        is_process_post = True
        is_skip_summary = mw.get_setting('mediawiker_skip_summary', False)
        self.sitecon = mw.get_connect()
        self.title = mw.get_title()
        if self.title:
            self.page = mw.get_page(self.sitecon, self.title)

            if self.page.can('edit'):

                if mw.get_setting('mediawiki_validate_revision_on_post', True) and self.view.settings().get('page_revision', 0) != self.page.revision:
                    is_process_post = sublime.ok_cancel_dialog('Page was changed on server, post page anyway? If not, new revision will be opened in new tab.')

                if is_process_post:
                    self.current_text = self.view.substr(sublime.Region(0, self.view.size()))
                    if not is_skip_summary:
                        summary_message = 'Changes summary (%s):' % mw.get_view_site()
                        mw.set_timeout_async(self.view.window().show_input_panel(summary_message, '', self.on_done, None, None), 0)
                    else:
                        mw.set_timeout_async(self.on_done, 0)
                else:
                    self.view.window().run_command('mediawiker_page', {'action': 'mediawiker_reopen_page', 'new_tab': True})
            else:
                mw.status_message('You have not rights to edit this page')
        else:
            mw.status_message('Can\'t publish page with empty title')
            return
Example #24
0
    def run(self, edit):
        # Get the body of the file
        reg = sublime.Region(0, self.view.size())
        self.text = self.view.substr(reg)

        # Get the Base64 encoded Auth String
        authentication = get_authentication(self, edit)
        if not authentication:
           return

        try:
            url = self.url + "&sysparm_action=get&JSON"
            url = url.replace("sys_id", "sysparm_sys_id")
            response_data = json.loads(http_call(authentication,url,{}))
            serverText = response_data['records'][0]['script']

            if self.text != serverText and sublime.ok_cancel_dialog("File has been updated on server. \nPress OK to Reload."):
                self.view.erase(edit, reg)
                self.view.begin_edit()
                self.view.insert(edit,0,serverText)
                self.view.end_edit(edit)
            return
        except (urllib2.HTTPError) as (e):
            err = 'Error %s' % (str(e.code))
        except (urllib2.URLError) as (e):
            err = 'Error %s' % (str(e.code))
        print err
    def run(self):
        user_settings = os.path.join(
            sublime.packages_path(),
            "User",
            "LaTeXTools.sublime-settings"
        )

        load_default = False
        if not os.path.exists(user_settings):
            migrate = sublime.ok_cancel_dialog(
                'You do not currently have a personalized '
                'LaTeXTools.sublime-settings file.\n\n'
                'Create a copy of the default settings file in '
                'your User directory?'
            )

            if migrate:
                sublime.active_window().run_command('latextools_migrate')
            else:
                load_default = True

        self.view = sublime.active_window().open_file(user_settings)

        if load_default:
            sublime.set_timeout(self.set_content, 1)
Example #26
0
    def remove_file(self, file, message):
        to_trash = get_setting(self.window.active_view(), 'jekyll_send_to_trash', False)

        if to_trash:
            message = message + (
                '\n\nYou seem to be using the `jekyll_send_to_trash` setting, so you '
                'can retrieve this file later in your system Trash or Recylcing Bin.'
            )
        else:
            message = message + (
                '\n\nThis action is permanent and irreversible since you are not using '
                'the `jekyll_send_to_trash` setting. Are you sure you want to continue?'
            )

        delete = sublime.ok_cancel_dialog(message, 'Confirm Delete')

        if delete is True:
            self.window.run_command('close_file')
            self.window.run_command('refresh_folder_list')

            if to_trash:
                send2trash(file)

            else:
                os.remove(file)

        else:
            return
 def run(self, **args):
     config = getPrefs(args["cmd"])
     if config != None:
         if (len(config) > 0):
             if args.get("batch", False) == True or (config.get("debug", None) != None and "all" in config["debug"] or "a" in config["debug"]):
                 args["cmd"] = [config["compiler"], config["filedir"]]
                 if config.get("scripts", None) != None:
                     if config["filedir"] == config["scripts"]:
                         if USER_SETTINGS.get("confirm_dangerous_batch_compilations", True) == True:
                             if not sublime.ok_cancel_dialog("Are you sure you want to batch compile all script sources in \"%s\"?\n\nThis folder may contain script sources that are supplied with Creation Kit and are a part of the base game. Compiling said script sources could lead to unintended behavior if they have been modified." % config["filedir"]):
                                 return
             else:
                 args["cmd"] = [config["compiler"], config["filename"]]
             args["cmd"].append("-f=%s" % config["flags"])
             args["cmd"].append("-i=%s" % config["import"])
             args["cmd"].append("-o=%s" % config["output"])
             for debugarg in config["debug"]:
                 if debugarg.startswith("-"):
                     args["cmd"].append("%s" % debugarg)
                 else:
                     args["cmd"].append("-%s" % debugarg)
             if args.get("batch", False) == True:
                 if config.get("debug", None) != None or ("all" not in config["debug"] and "a" not in config["debug"]):
                     args["cmd"].append("-all")
                 del args["batch"]
             args["working_dir"] = os.path.dirname(config["compiler"])
             self.window.run_command("exec", args)
         else:
             sublime.status_message("No configuration for %s" % os.path.dirname(args["cmd"]))
def _get_cache():
    if _ST3:
        cache_path = os.path.normpath(
            os.path.join(sublime.cache_path(), "LaTeXTools"))
    else:
        cache_path = os.path.normpath(
            os.path.join(sublime.packages_path(), "User"))

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

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

        if gen_cache:
            sublime.active_window().run_command("latex_gen_pkg_cache")
    else:
        with open(pkg_cache_file) as f:
            cache = json.load(f)
    return cache
    def run(self, edit):
        try:
            configuration = PluginUtils.get_project_configuration(self.view.window(), self.view.file_name())

            base_path = configuration.get("base-path")
            test_path = configuration.get("test-path")

            if not base_path or not test_path:
                sublime.message_dialog("This project has not been configured for Jasmine boilerplate generation.\n\nRight click on the base and test folders to configure.")
                return

            output_files = AngularJasmineBoilerplateCommand.run_command(self, base_path, test_path)

            if output_files[0].find(OUTPUT_ALREADY_EXISTS) != -1: # TODO: Update when we support multiple files
                if sublime.ok_cancel_dialog("Boilerplate file " + output_files[0], "Overwrite"):
                    output_files = AngularJasmineBoilerplateCommand.run_command(self, base_path, test_path, True)
                else:
                    return

            for file in output_files:
                if file:
                    self.view.window().open_file(test_path + "/" + file)
        except:
            print("Unexpected error({0}): {1}".format(sys.exc_info()[0], sys.exc_info()[1]))
            traceback.print_tb(sys.exc_info()[2])
            sublime.message_dialog("Unable to generate Jasmine boilerplate.\n\nEnsure that the AngularJS service or controller is annotated correctly.")
  def run_script_on_file(self, temp_file_path):
    try:
      node_path = PluginUtils.get_node_path()
      script_path = PLUGIN_FOLDER + "/scripts/run.js"
      file_path = self.view.file_name()
      cmd = [node_path, script_path, temp_file_path, file_path or "?"]
      output = PluginUtils.get_output(cmd)

      # Make sure the correct/expected output is retrieved.
      if output.find(OUTPUT_VALID) != -1:
        return output

      msg = "Command " + '" "'.join(cmd) + " created invalid output."
      print(output)
      raise Exception(msg)

    except:
      # Something bad happened.
      print("Unexpected error({0}): {1}".format(sys.exc_info()[0], sys.exc_info()[1]))

      # Usually, it's just node.js not being found. Try to alleviate the issue.
      msg = "Node.js was not found in the default path. Please specify the location."
      if not sublime.ok_cancel_dialog(msg):
        msg = "You won't be able to use this plugin without specifying the path to node.js."
        sublime.error_message(msg)
      else:
        PluginUtils.open_sublime_settings(self.view.window())
Example #31
0
    def run(self, path=""):

        multi_importer = sublime_plugin.multi_importer
        zippaths = []
        for loader in multi_importer.loaders:
            zippath = loader.zippath
            if is_a_package(zippath):
                zippaths.append(zippath)

        zippaths_total = len(zippaths)
        if sublime.ok_cancel_dialog(
                "Extract %s to the Packages directory? This may take a while."
                % zippaths_total):
            for zippath in zippaths:
                extract_package(zippath, path)
            _msg("Completed extracting %s packages" % zippaths_total)
Example #32
0
    def restart(self, view, edit):
        repl_restart_args = view.settings().get("repl_restart_args")
        if not repl_restart_args:
            sublime.message_dialog("No restart parameters found")
            return False
        rv = self.repl_view(view)
        if rv:
            if rv.repl and rv.repl.is_alive() and not sublime.ok_cancel_dialog(
                    "Still running. Really restart?"):
                return False
            rv.on_close()  # yes on_close, delete rv from

        view.insert(edit, view.size(), RESTART_MSG)
        repl_restart_args["view_id"] = view.id()
        self.open(view.window(), **repl_restart_args)
        return True
Example #33
0
    def run(self, edit, cmd=None, prog=None, confirmation=None):
        # set TextGetter before get_text() because get_text may change cursor locations.

        if confirmation:
            ok = sublime.ok_cancel_dialog(confirmation)
            if not ok:
                return

        sender = TextSender.initialize(self.view, prog=prog)
        if cmd:
            cmd = self.resolve(cmd)
        else:
            getter = TextGetter.initialize(self.view)
            cmd = getter.get_text()

        sublime.set_timeout_async(lambda: sender.send_text(cmd))
Example #34
0
    def run(self, paths, current_file=False):
        if not self.is_enabled():
            return

        confirm = bool(
            sublime.ok_cancel_dialog(
                'This will delete your local copy as well. Are you sure you want do do this?'
            ))
        if not confirm:
            return

        if paths is None and current_file:
            paths = [self.window.active_view().file_name()]

        for path in paths:
            Listener.delete_buf(path)
Example #35
0
 def run(self, edit):
     files = self.get_marked() or self.get_selected()
     if files:
         # Yes, I know this is English.  Not sure how Sublime is translating.
         if len(files) == 1:
             msg = "Delete {}?".format(files[0])
         else:
             msg = "Delete {} items?".format(len(files))
         if sublime.ok_cancel_dialog(msg):
             for filename in files:
                 fqn = join(self.path, filename)
                 if isdir(fqn):
                     shutil.rmtree(fqn)
                 else:
                     os.remove(fqn)
             self.view.run_command('dired_refresh')
Example #36
0
    def validate_num_commits(self, commits):
        if commits is None:
            return False

        if len(commits) == 0:
            sublime.error_message('No commits selected.')
            return False

        if len(commits) > 5 and get_setting('git_blame_warn_multiple_tabs',
                                            True):
            if not sublime.ok_cancel_dialog(
                    'This will open %s tabs. Are you sure you want to continue?'
                    % len(commits), 'Open tabs'):
                return False

        return True
Example #37
0
    def run(self, edit):
        if self.view.settings().get("git_savvy.commit_on_close"):
            message_txt = extract_commit_message(self.view).strip()
            if message_txt:
                self.view.run_command("gs_commit_view_do_commit",
                                      {"message": message_txt})
            else:
                self.view.close()

        elif self.view.settings().get("git_savvy.prompt_on_abort_commit"):
            message_txt = extract_commit_message(self.view).strip()
            if not message_txt or sublime.ok_cancel_dialog(CONFIRM_ABORT):
                self.view.close()

        else:
            self.view.close()
Example #38
0
 def on_project_path(self, path):
     self.project_path = path
     self.project_path_escaped = path.replace("/", "\\\\\\\\")
     self.project_name = os.path.basename(self.project_path)
     if os.path.exists(self.project_path):
         decision = sublime.ok_cancel_dialog(
             "Something already exists at " + self.project_path +
             ".\nDo you want to create project in that folder?" +
             "\n(Existing objects will not be overwritten)")
         if decision:
             self.create_project()
     else:
         if not self.project_files_folder:
             self.create_project()
         else:
             self.get_project_name()
Example #39
0
 def remove_project(self, project):
     ok = sublime.ok_cancel_dialog(
         "Remove project %s from Project Manager?" % project)
     if ok:
         pfile = self.project_file_name(project)
         if self.which_projects_dir(pfile):
             self.close_project(project)
             os.unlink(self.project_file_name(project))
             os.unlink(self.project_workspace(project))
         else:
             for pdir in self.projects_fpath:
                 j = JsonFile(os.path.join(pdir, "library.json"))
                 data = j.load([])
                 if pfile in data:
                     data.remove(pfile)
                     j.save(data)
Example #40
0
 def run(self, _):
     file_path = self.view.file_name()
     if file_path:
         (_, ext) = os.path.splitext(file_path)
         if ext == NOTE_EXTENSION:
             should_del = sublime.ok_cancel_dialog(
                 "Delete Zamek note? This will also delete the file from disk.",
                 "Delete")
             if should_del:
                 registry = load_registry(REGISTRY_PATH)
                 if registry:
                     registry.remove_note(note_from_path(file_path))
                     os.remove(file_path)
                     save_registry(registry, REGISTRY_PATH)
         else:
             sublime.error_message("Not a Zamek note!")
Example #41
0
 def update(self, event, producer, data=None):
     if event == collab_event.INCOMING_SESSION_REQUEST:
         logger.debug('incoming session request: ' + str(data))
         username = data[0]
         # someone wants to collaborate with you! do you want to accept?
         acceptRequest = sublime.ok_cancel_dialog(
             username + ' wants to collaborate with you!')
         if acceptRequest == True:
             producer.acceptSessionRequest(data[0], data[1], data[2])
         else:
             producer.rejectSessionRequest(data[0])
     elif event == collab_event.ESTABLISHED_SESSION:
         logger.debug('session established, opening view selector')
         self.chooseView(session=producer)
     elif event == collab_event.FAILED_SESSION:
         pass
Example #42
0
    def on_done(self, old, new):
        """Handle the tab duplication when the user is done with the input panel."""

        new_path = os.path.dirname(new)
        if os.path.exists(new_path) and os.path.isdir(new_path):
            if not os.path.exists(new) or sublime.ok_cancel_dialog("Overwrite %s?" % new, "Replace"):
                try:
                    with open(old, 'rb') as f:
                        text = f.read()

                    with open(new, 'wb') as f:
                        f.write(text)

                    self.window.open_file(new)
                except Exception:
                    sublime.status_message("Unable to duplicate")
Example #43
0
 def import_sublime_project(self):
     pfile = self.window.project_file_name()
     if not pfile:
         sublime.message_dialog("Project file not found!")
         return
     if self.which_projects_dir(pfile):
         sublime.message_dialog(
             "This project was created by Project Manager!")
         return
     ok = sublime.ok_cancel_dialog("Import %s?" % os.path.basename(pfile))
     if ok:
         j = JsonFile(os.path.join(self.primary_dir, "library.json"))
         data = j.load([])
         if pfile not in data:
             data.append(pfile)
             j.save(data)
Example #44
0
 def decode_stdout(self, stdout, savvy_settings):
     fallback_encoding = savvy_settings.get("fallback_encoding")
     silent_fallback = savvy_settings.get("silent_fallback")
     try:
         return stdout.decode()
     except UnicodeDecodeError as unicode_err:
         try:
             return stdout.decode("latin-1")
         except UnicodeDecodeError as unicode_err:
             if silent_fallback or sublime.ok_cancel_dialog(UTF8_PARSE_ERROR_MSG, "Fallback?"):
                 try:
                     return stdout.decode(fallback_encoding)
                 except UnicodeDecodeError as fallback_err:
                     sublime.error_message(FALLBACK_PARSE_ERROR_MSG)
                     raise fallback_err
             raise unicode_err
Example #45
0
	def run(self):
		if sublime.ok_cancel_dialog("Are you sure you want to upgrade Code4Brownies to the latest version?", "Yes"):
			package_path = os.path.join(sublime.packages_path(), "C4BStudent")
			if not os.path.isdir(package_path):
				os.mkdir(package_path)
			c4b_py = os.path.join(package_path, "Code4Brownies.py")
			c4b_menu = os.path.join(package_path, "Main.sublime-menu")
			c4b_version = os.path.join(package_path, "VERSION")
			try:
				urllib.request.urlretrieve("https://raw.githubusercontent.com/vtphan/Code4Brownies/master/src/C4BStudent/Code4Brownies.py", c4b_py)
				urllib.request.urlretrieve("https://raw.githubusercontent.com/vtphan/Code4Brownies/master/src/C4BStudent/Main.sublime-menu", c4b_menu)
				urllib.request.urlretrieve("https://raw.githubusercontent.com/vtphan/Code4Brownies/master/src/VERSION", c4b_version)
				version = open(c4b_version).read()
				sublime.message_dialog("Code4Brownies has been upgraded to version %s" % version)
			except:
				sublime.message_dialog("A problem occurred during upgrade.")
Example #46
0
 def _remove_project(self, project):
     answer = sublime.ok_cancel_dialog('Remove "%s" from Project Manager?' % project)
     if answer is True:
         pfile = self.project_file_name(project)
         if self.which_project_dir(pfile):
             self.close_project_by_name(project)
             os.remove(self.project_file_name(project))
             os.remove(self.project_workspace(project))
         else:
             for pdir in self.projects_path:
                 j = JsonFile(os.path.join(pdir, 'library.json'))
                 data = j.load([])
                 if pfile in data:
                     data.remove(pfile)
                     j.save(data)
         sublime.status_message('Project "%s" is removed.' % project)
Example #47
0
    def warning_msg(self):
        cancel_op = False
        s = sublime.load_settings(SETTINGS_FILE)
        show_warning = s.get('show_auto_correct_warning')
        if show_warning:
            cancel_op = not sublime.ok_cancel_dialog("""
Attention! You are about to run auto correction on the current file. 

The contents of the current buffer will be overwritten by RuboCop. Afterwards, you need to save these changes manually.

Do you want to continue?

(You can disable this message in the settings.)
      """)

        return cancel_op
Example #48
0
def check_binary():
    # If we couldn't find the binary.
    if (which(binary) == None):
        # Try to guess the correct setting.
        if (which(default_binary) != None):
            # Looks like clang-format is in the path, remember that.
            set_path(default_binary)
            return True
        # We suggest setting a new path using an input panel.
        msg = "The clang-format binary was not found. Set a new path?"
        if sublime.ok_cancel_dialog(msg):
            update_path()
            return True
        else:
            return False
    return True
Example #49
0
    def disable_rle(self, edit):
        """Disable raw line ending mode."""

        # Save raw line ending changes
        if self.view.is_dirty():
            if sublime.ok_cancel_dialog("Raw Line Edit:\nFile has unsaved changes.  Save?", "Save"):
                self.view.run_command("save")

        # Get the settings
        settings = self.view.settings()
        file_name = settings.get("RawLineEditFilename")
        syntax = settings.get("RawLineEditSyntax")
        use_glyph = settings.get("RawLineEditGlyph")
        buffer_endings = settings.get("RawLineBuffer", None)

        # Strip the buffer of gyphs and prepare to write
        # the stripped buffer back to the view
        if buffer_endings is not None:
            RawLineTextBuffer.set_buffer(self.view, use_glyph)

        # Open temp view if only one view is open,
        # so not to close the window when we remove the view.
        window = self.view.window()
        temp = None
        if len(window.views()) <= 1:
            temp = window.new_file()

        # Close raw line view
        window.focus_view(self.view)
        window.run_command("close_file")

        # Open the file on disk
        new_view = window.open_file(file_name)

        # Close temp view if needed
        if temp is not None:
            window.focus_view(temp)
            window.run_command("close_file")

        # Set view settings
        window.focus_view(new_view)
        new_view.set_syntax_file(syntax)

        # Reapply unsaved buffer if needed
        if buffer_endings is not None:
            new_view.set_line_endings(buffer_endings)
            RawLineTextBuffer.check_loading(new_view)
Example #50
0
    def run(self, edit):
        if utils.props.get_setting('offline_mode'):
            return

        is_process_post = True
        is_skip_summary = utils.props.get_setting('skip_summary', False)
        self.title = utils.get_title()
        if self.title:
            self.page = utils.api.get_page(self.title)

            if utils.api.page_can_edit(self.page):

                if utils.props.get_setting(
                        'validate_revision_on_post',
                        True) and utils.props.get_view_setting(
                            self.view, 'page_revision',
                            0) != utils.api.page_attr(self.page, 'revision'):
                    is_process_post = sublime.ok_cancel_dialog(
                        'Page was changed on server, post page anyway? If not, new revision will be opened in new tab.'
                    )

                if is_process_post:
                    self.current_text = self.view.substr(
                        sublime.Region(0, self.view.size()))
                    if not is_skip_summary:
                        summary_message = 'Changes summary (%s):' % utils.get_view_site(
                        )
                        utils.set_timeout_async(
                            self.view.window().show_input_panel(
                                summary_message, '', self.on_done, None, None),
                            0)
                    else:
                        utils.set_timeout_async(self.on_done, 0)
                else:
                    self.view.window().run_command(
                        utils.cmd('page'), {
                            'action': utils.cmd('show_page'),
                            'action_params': {
                                'title': self.title,
                                'new_tab': True
                            }
                        })
            else:
                utils.status_message(utils.api.PAGE_CANNOT_EDIT_MESSAGE)
        else:
            utils.status_message('Can\'t publish page with empty title')
            return
Example #51
0
 def import_sublime_project(self):
     pfile = pretty_path(self.window.project_file_name())
     if not pfile:
         sublime.message_dialog('Project file not found!')
         return
     if self.which_project_dir(pfile):
         sublime.message_dialog(
             'This project was created by Project Manager!')
         return
     answer = sublime.ok_cancel_dialog('Import %s?' %
                                       os.path.basename(pfile))
     if answer is True:
         j = JsonFile(os.path.join(self.primary_dir, 'library.json'))
         data = j.load([])
         if pfile not in data:
             data.append(pfile)
             j.save(data)
Example #52
0
    def revert_string_template(self, edit):
        """
    恢复字符串模板中的图片, 将图片还原到原始目录下

    :param edit: <object>
    :return:
    """

        sel_result = os.path.exists(
            self.target_file
        ) and sublime.ok_cancel_dialog(
            'Sipaste:: You are restoring the image in the trash, Do you want to continue?'
        )
        move_file(self.target_file,
                  self.image_path[0][0]) if sel_result else self.view.erase(
                      edit,
                      self.view.sel()[0])
Example #53
0
    def run(self):
        """Run the command."""
        if not sublime.ok_cancel_dialog(
            'You will be asked for the linter name. Please enter the name '
            'of the linter binary (including dashes), NOT the name of the language being linted. '
            'For example, to lint CSS with csslint, the linter name is '
            '“csslint”, NOT “css”.',
            'I understand'
        ):
            return

        self.window.show_input_panel(
            'Linter name:',
            '',
            on_done=self.copy_linter,
            on_change=None,
            on_cancel=None)
Example #54
0
    def on_input_package_path(self, package_path):
        # Check input
        if not package_path:
            message = 'Invalid path, do you want to try again?'
            if not sublime.ok_cancel_dialog(message, "Try Again?"): return
            self.window.show_input_panel("Please Input Name: ", "",
                                         self.on_input_extractto, None, None)
            return

        base = os.path.split(package_path)[0]
        if not os.path.exists(base):
            os.makedirs(base)

        with open(package_path, "wb") as fp:
            fp.write(util.format_xml(self.package_xml_content))

        view = sublime.active_window().open_file(package_path)
Example #55
0
            def on_done(data):
                datar = data.split(",")
                if len(datar) > 2 or len(datar) == 1:
                    sublime.message_dialog("Error: Wrong inputted data.")
                    return

                ok = sublime.ok_cancel_dialog(
                    "Your client id and secret are\n{}\n{}\nAre those ok?".
                    format(datar[0].strip(), datar[1].strip()))
                if ok is not True:
                    if self.flag == "gist":
                        exe = "gislacks_authgist"
                    elif self.flag == "slack":
                        exe = "gislacks_authslack"
                    self.sview.run_command(exe)
                    return
                self.getCode(datar)
    def open_any(self, files):
        if len(files) == 0:
            sublime.status_message("Not a valid file")
            return

        opened = False
        for file in files:
            if not opened:
                opened = self.open(file)

        if opened:
            return

        first = files[0]
        if sublime.ok_cancel_dialog("Create file? " + first):
            self.create(first)
            self.window.open_file(first)
Example #57
0
    def run(self, edit):
        if self.data is not None:
            self.replace(edit)
            return

        aggresive_level = get_settings(self.view, 'aggressive', 0)
        if aggresive_level > 0:
            if not sublime.ok_cancel_dialog(
                    'You have an aggressive level of {} this may cause '
                    'anaconda to change things that you don\'t really want to '
                    'change.\n\nAre you sure do you want to continue?'.format(
                        aggresive_level)):
                return

        self.code = self.view.substr(sublime.Region(0, self.view.size()))
        settings = {
            'aggressive':
            aggresive_level,
            'list-fixes':
            get_settings(self.view, 'list-fixes', False),
            'autoformat_ignore':
            get_settings(self.view, 'autoformat_ignore', []),
            'autoformat_select':
            get_settings(self.view, 'autoformat_select', []),
            'pep8_max_line_length':
            get_settings(self.view, 'pep8_max_line_length', 79)
        }
        try:
            messages = {
                'start': 'Autoformatting please wait... ',
                'end': 'Autoformatting done!'
            }
            self.pbar = ProgressBar(messages)
            self.pbar.start()
            self.view.set_read_only(True)

            data = {
                'vid': self.view.id(),
                'code': self.code,
                'method': 'autoformat',
                'settings': settings
            }
            Worker().execute(self.get_data, **data)

        except:
            logging.error(traceback.format_exc())
Example #58
0
    def run(self, paths, current_file=False):
        if not self.is_enabled():
            return

        if paths is None and current_file:
            paths = [self.window.active_view().file_name()]

        if not hasattr(sublime, 'yes_no_cancel_dialog'):
            unlink = bool(sublime.ok_cancel_dialog('Delete? Select cancel to remove from the workspace without deleting.', 'Delete'))
        else:
            ret = sublime.yes_no_cancel_dialog("What should I do with\n%s" % "\n".join(paths[:5]), "Delete!", "Just Remove from Workspace.")
            if ret == 0:
                return
            unlink = ret == 1

        for path in paths:
            G.AGENT.delete_buf(path, unlink)
Example #59
0
	def run(self, edit, encoding=None, stamp=None, detect_on_fail=False):
		view = self.view
		if encoding:
			view.settings().set('force_encoding', encoding)
			origin_encoding = view.settings().get('origin_encoding')
			# convert only when ST2 can't load file properly
			run_convert = (view.encoding() == view.settings().get('fallback_encoding'))
			if origin_encoding:
				if origin_encoding == encoding:
					return
				view.set_scratch(False)
				run_convert = False
			init_encoding_vars(view, encoding, run_convert, stamp)
			return
		else:
			encoding = view.settings().get('origin_encoding')
		if not encoding:
			return
		file_name = view.file_name()
		if not (file_name and os.path.exists(file_name)):
			return
		# try fast decode
		fp = None
		try:
			fp = codecs.open(file_name, 'rb', encoding, errors='strict')
			contents = fp.read()
		except UnicodeDecodeError, e:
			if detect_on_fail:
				detect(view, file_name, view.encoding())
				return
			if CONFIRM_IS_AVAILABLE:
				if sublime.ok_cancel_dialog('Errors occurred while converting %s file with %s encoding.\n\n'
						'Continue to load this file using %s encoding (malformed data will be replaced by a marker)?'
						'\n\nPress "Cancel" to choose another encoding manually.' %
						(os.path.basename(file_name), encoding, encoding)):
					fp.close()
					fp = codecs.open(file_name, 'rb', encoding, errors='replace')
					contents = fp.read()
				else:
					show_selection(view)
					return
			else:
				view.set_status('origin_encoding', 'Errors occurred while converting %s file with %s encoding' %
						(os.path.basename(file_name), encoding))
				show_selection(view)
				return
Example #60
0
    def do_push(self, remote, branch, force=False, remote_branch=None):
        """
        Perform `git push remote branch`.
        """
        savvy_settings = sublime.load_settings("GitSavvy.sublime-settings")
        if force and savvy_settings.get("confirm_force_push"):
            if not sublime.ok_cancel_dialog(CONFIRM_FORCE_PUSH):
                return

        sublime.status_message(START_PUSH_MESSAGE)
        self.push(remote,
                  branch,
                  set_upstream=self.set_upstream,
                  force=force,
                  remote_branch=remote_branch)
        sublime.status_message(END_PUSH_MESSAGE)
        util.view.refresh_gitsavvy(self.window.active_view())