def do_diff(self, diff_args):
        """Run a diff and display the changes.

        Args:
            diff_args: the arguments to the diff.
        """
        self.diff_args = diff_args

        try:
            # Create the diff parser
            cwd = os.path.dirname(self.window.active_view().file_name())
            self.parser = DiffParser(self.diff_args, cwd)
        except NoVCSError:
            # No changes; say so
            sublime.message_dialog(
                "This file does not appear to be under version control " +
                "(Git or SVN).")
            return

        if not self.parser.changed_hunks:
            # No changes; say so
            sublime.message_dialog("No changes to report...")
        else:
            # Show the list of changed hunks
            self.list_changed_hunks()
Exemple #2
0
    def run_async(self):
        short_hash = self.get_selected_short_hash()
        if not short_hash:
            return
        if self.interface.entries[-1].short_hash == short_hash:
            sublime.status_message("Unable to move last commit down.")
            return

        commit_chain = [
            self.ChangeTemplate(orig_hash=entry.long_hash,
                                move=entry.short_hash == short_hash,
                                do_commit=True,
                                msg=entry.raw_body,
                                datetime=entry.datetime,
                                author="{} <{}>".format(entry.author, entry.email))
            for entry in self.interface.entries
        ]

        # Take the change to move and swap it with the one following.
        for idx, commit in enumerate(commit_chain):
            if commit.move:
                commit_chain[idx], commit_chain[idx+1] = commit_chain[idx+1], commit_chain[idx]
                break

        try:
            self.make_changes(commit_chain)
        except:
            sublime.message_dialog("Unable to move commit, most likely due to a conflict.")
    def run(self, edit, **kwargs):
        vid = self.view.id()

        if vid in persist.errors and persist.errors[vid]:
            method(self, self.view, persist.errors[vid], persist.highlights[vid], **kwargs)
        else:
            sublime.message_dialog('No lint errors.')
	def run(self, edit):		
		sels = self.view.sel()		
		if self.isRegionEmpty(sels[0]):
			sublime.message_dialog("Please select list by pressing ctrl+A")
		else:
			if self.convertListTocsv(sels,edit) =="true":
				sublime.status_message("Conversion Done")
 def handler(self, name, data):
     if name == 'create_user':
         del data['name']
         try:
             floorc = BASE_FLOORC + '\n'.join(['%s %s' % (k, v) for k, v in data.items()]) + '\n'
             with open(G.FLOORC_PATH, 'wb') as floorc_fd:
                 floorc_fd.write(floorc.encode('utf-8'))
             utils.reload_settings()
             if False in [bool(x) for x in (G.USERNAME, G.API_KEY, G.SECRET)]:
                 sublime.message_dialog('Something went wrong. You will need to sign up for an account to use Floobits.')
                 api.send_error({'message': 'No username or secret'})
             else:
                 p = os.path.join(G.BASE_DIR, 'welcome.md')
                 with open(p, 'wb') as fd:
                     text = welcome_text % (G.USERNAME, self.host)
                     fd.write(text.encode('utf-8'))
                 d = utils.get_persistent_data()
                 d['auto_generated_account'] = True
                 utils.update_persistent_data(d)
                 G.AUTO_GENERATED_ACCOUNT = True
                 sublime.active_window().open_file(p)
         except Exception as e:
             msg.error(e)
         try:
             d = utils.get_persistent_data()
             d['disable_account_creation'] = True
             utils.update_persistent_data(d)
         finally:
             self.stop()
Exemple #6
0
 def handle_results(results):
     if len(results) > 1:
         self.ask_user_result(results)
     elif results:  # len(results) == 1
         self.goto(results[0])
     else:
         message_dialog('Symbol "{0}" not found'.format(symbol))
Exemple #7
0
    def popup_error_list(self):
        """ Display a popup list of the errors found """
        view_id = self.view.id()

        if not view_id in PYLINTER_ERRORS:
            return

        # No errors were found
        if len(PYLINTER_ERRORS[view_id]) == 1:
            sublime.message_dialog("No Pylint errors found")
            return

        errors = [(key + 1, value)
                  for key, value in PYLINTER_ERRORS[view_id].items()
                  if key != 'visible']
        line_nums, panel_items = zip(*sorted(errors,
                                             key=lambda error: error[1]))

        def on_done(selected_item):
            """ Jump to the line of the item that was selected from the list """
            if selected_item == -1:
                return
            self.view.run_command("goto_line",
                                  {"line": line_nums[selected_item]})

        self.view.window().show_quick_panel(list(panel_items), on_done)
    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.")
Exemple #9
0
    def getPackageData(self):
        window = self.window
        view = window.active_view()
        selText = view.sel()[0]
        xt = str(window.active_view().file_name())

        scope = (view.scope_name(0).split(" ")[0].split(".")[1])
        selected = view.substr(selText)

        try:
            if scope == "java":
                sublime.status_message("LangDocs: Looking up package definition")
                doc = getJavaPackDoc(selected)[0]
                url = getJavaPackDoc(selected)[1]

                if len(doc) > 2:
                    try:
                        doc =  "<h1>%s documentation</h1><br>%s ... <br><br>Read more at: \"<a href=\"%s\">%s</a>\"" % (selected, doc, url, url)
                        view.show_popup("<style>%s</style>%s" % (css, doc), max_width=700,
                            on_navigate=lambda x:(webbrowser.open(url)))

                    except:
                        doc =  "%s documentation\n\n%s ... \n\nRead more at: \"%s\"" % (selected, doc, url)
                        sublime.message_dialog(doc)

                else:
                    sublime.status_message("LangDocs: Can't find documentation")
        except:
            sublime.status_message("LangDocs: Can't find documentation")
Exemple #10
0
    def page_open(self, title):

        if self.new_tab:
            view = sublime.active_window().new_file()
            view.settings().set('mediawiker_site', self.site_active)
        else:
            view = self.view

        is_writable = False
        sitecon = mw.get_connect()
        page = mw.get_page(sitecon, title)
        is_writable, text = mw.get_page_text(page)

        if is_writable or text:

            if is_writable and not text:
                mw.status_message('Wiki page %s is not exists. You can create new..' % (title))
                text = '<!-- New wiki page: Remove this with text of the new page -->'
            # insert text
            view.run_command('mediawiker_insert_text', {'position': 0, 'text': text, 'with_erase': True})
            mw.status_message('Page [[%s]] was opened successfully from "%s".' % (title, mw.get_view_site()), replace=['[', ']'])
            mw.set_syntax(page=page)
            view.settings().set('mediawiker_is_here', True)
            view.settings().set('mediawiker_wiki_instead_editor', mw.get_setting('mediawiker_wiki_instead_editor'))
            view.set_name(title)

            view.set_scratch(True)
            # own is_changed flag instead of is_dirty for possib. to reset..
            view.settings().set('is_changed', False)
        else:
            sublime.message_dialog('You have not rights to view this page.')
            view.close()
Exemple #11
0
 def extract(self):
   sep = os.sep
   if self.NODE_JS_TAR_EXTENSION != ".zip" :
     with tarfile.open(self.NODE_JS_BINARY_TARFILE_FULL_PATH, "r:gz") as tar :
       for member in tar.getmembers() :
         member.name = sep.join(member.name.split(sep)[1:])
         tar.extract(member, node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
   else :
     if node_variables.NODE_JS_OS == "win" :
       import string
       from ctypes import windll, c_int, c_wchar_p
       UNUSUED_DRIVE_LETTER = ""
       for letter in string.ascii_uppercase:
         if not os.path.exists(letter+":") :
           UNUSUED_DRIVE_LETTER = letter+":"
           break
       if not UNUSUED_DRIVE_LETTER :
         sublime.message_dialog("Can't install node.js and npm! UNUSUED_DRIVE_LETTER not found.")
         return
       DefineDosDevice = windll.kernel32.DefineDosDeviceW
       DefineDosDevice.argtypes = [ c_int, c_wchar_p, c_wchar_p ]
       DefineDosDevice(0, UNUSUED_DRIVE_LETTER, node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
       try:
         with zipfile.ZipFile(self.NODE_JS_BINARY_TARFILE_FULL_PATH, "r") as zip_file :
           for member in zip_file.namelist() :
             if not member.endswith("/") :
               with zip_file.open(member) as node_file:
                 with open(UNUSUED_DRIVE_LETTER + "\\"+ member.replace("node-"+self.NODE_JS_VERSION+"-"+node_variables.NODE_JS_OS+"-"+node_variables.NODE_JS_ARCHITECTURE+"/", ""), "wb+") as target :
                   shutil.copyfileobj(node_file, target)
             elif not member.endswith("node-"+self.NODE_JS_VERSION+"-"+node_variables.NODE_JS_OS+"-"+node_variables.NODE_JS_ARCHITECTURE+"/"):
               os.mkdir(UNUSUED_DRIVE_LETTER + "\\"+ member.replace("node-"+self.NODE_JS_VERSION+"-"+node_variables.NODE_JS_OS+"-"+node_variables.NODE_JS_ARCHITECTURE+"/", ""))
       except Exception as e:
         print("Error: "+traceback.format_exc())
       finally:
         DefineDosDevice(2, UNUSUED_DRIVE_LETTER, node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
Exemple #12
0
    def make_changes(self, commit_chain, description, base_commit=None):
        base_commit = base_commit or self.interface.base_commit()
        branch_name, ref, changed_files = self.interface.get_branch_state()
        success = True

        if len(changed_files):
            sublime.message_dialog(
                "Unable to perform rebase actions while repo is in unclean state."
            )
            return

        try:
            self.rewrite_active_branch(
                base_commit=base_commit,
                commit_chain=commit_chain
                )

        except Exception as e:
            success = False
            raise e

        finally:
            self.interface.complete_action(branch_name, ref, success, description)

        util.view.refresh_gitsavvy(self.view)
Exemple #13
0
    def run_async(self):
        short_hash = self.get_selected_short_hash()
        if not short_hash:
            return
        if self.interface.entries[-1].short_hash == short_hash:
            sublime.status_message("Unable to move last commit down.")
            return

        move_idx, to_move, entry_before_move = self.get_idx_entry_and_prev(short_hash)

        commit_chain = [
            self.ChangeTemplate(orig_hash=entry.long_hash,
                                move=entry.short_hash == short_hash,
                                do_commit=True,
                                msg=entry.raw_body,
                                datetime=entry.datetime,
                                author="{} <{}>".format(entry.author, entry.email))
            for entry in self.interface.entries[move_idx:]
        ]

        # Take the change to move and swap it with the one following.
        commit_chain[0], commit_chain[1] = commit_chain[1], commit_chain[0]

        try:
            self.make_changes(commit_chain, "moved " + short_hash + " down", entry_before_move.long_hash)
            move_cursor(self.view, 2)
        except:
            sublime.message_dialog("Unable to move commit, most likely due to a conflict.")
    def create_output(self):
        self.sourceFilePath = self.inputView.file_name()
        self.outputFileName = Tool.get_js_file_name(Tool.get_file_name(self.sourceFilePath))
        self.outputTempDir = tempfile.gettempdir()
        # print(self.outputTempDir)
        self.outputFilePath = path.join(self.outputTempDir, self.outputFileName)

        no_wrapper = settings_get('noWrapper', True)
        args = []
        if no_wrapper:
            args = ['-b'] + args
        args = args + ["-m", "-o", self.outputTempDir, self.sourceFilePath]

        res = run("coffee", args)
        if not res["okay"]:
            sublime.message_dialog("Error. See console.")
            print(res["err"])
            return
        # create new tab
        self.outputView = self.inputView.window().open_file(self.outputFilePath)
        # move it to second column
        self.outputView.window().focus_group(1)
        self.outputView.window().set_view_index(self.outputView, self.outputView.window().active_group(), 0)
        # self.outputView.window().focus_group(0)
        self.inputView.window().focus_view(self.inputView)
    def on_post_save(self, view):
        if not self.is_enabled(view):
            return
        compile_on_save = settings_get('compileOnSave', True)
        if compile_on_save is True:
            print("Compiling on save...")
            view.run_command("compile")
            show_compile_output_on_save = settings_get('showOutputOnSave', True)
            if show_compile_output_on_save is True and isCoffee() is True and RunScriptCommand.PANEL_IS_OPEN is True:
                print("Updating output panel...")
                view.run_command("compile_output")

        watch_save = settings_get('watchOnSave', True)
        if watch_save:
            viewID = view.id()
            if viewID in watchers:
                watchers[viewID].refresh()

        if settings_get("checkSyntaxOnSave", True):
            args = ['-b', '-p']
            if isLitCoffee(view):
                args = ['-l'] + args
            res = brew(args, Text.get(view))
            if res["okay"] is True:
                sublime.status_message("Syntax is valid.")
            else:
                status = res["err"].split("\n")[0]
                sublime.message_dialog('Syntax error: %s' % status)

        if settings_get("lintOnSave", True):
            view.run_command("lint")
Exemple #16
0
    def run_async(self):
        """
        Display a panel of all remotes defined for the repo, then proceed to
        `on_select_remote`.  If no remotes are defined, notify the user and
        proceed no further.
        """
        self.interface = ui.get_interface(self.view.id())
        selection, line = self.interface.get_selection_line()
        if not line:
            return

        local_region = self.view.get_regions("git_savvy_interface.branch_list")[0]
        if not local_region.contains(selection):
            sublime.message_dialog("You can only setup tracking for local branches.")
            return

        segments = line.strip("▸ ").split(" ")
        self.local_branch = segments[1]

        self.remotes = list(self.get_remotes().keys())

        if not self.remotes:
            self.view.window().show_quick_panel(["There are no remotes available."], None)
        else:
            self.view.window().show_quick_panel(
                self.remotes,
                self.on_select_remote,
                flags=sublime.MONOSPACE_FONT
                )
            def delayed_settings_restore():
                if type == 'upgrade' and package in self.old_syntaxes:
                    for view_syntax in self.old_syntaxes[package]:
                        view, syntax = view_syntax
                        view.settings().set('syntax', syntax)

                if type == 'upgrade' and package in self.old_color_schemes:
                    for view_scheme in self.old_color_schemes[package]:
                        view, scheme = view_scheme
                        view.settings().set('color_scheme', scheme)

                if type == 'upgrade' and self.old_theme_package == package:
                    settings.set('theme', self.old_theme)
                    sublime.message_dialog(text.format(
                        u'''
                        Package Control

                        Your active theme was just upgraded. You may see some
                        graphical corruption until you restart Sublime Text.
                        '''
                    ))

                if type == 'upgrade' and self.old_color_scheme_package == package:
                    settings.set('color_scheme', self.old_color_scheme)

                sublime.save_settings(preferences_filename())
Exemple #18
0
    def run(self):
        global diffView
        text1 = self.left.substr(sublime.Region(0, self.left.size()))

        if isinstance(self.right, unicode):
            text2 = open(self.right, 'rb').read().decode('utf-8', 'replace')
        else:
            text2 = self.right.substr(sublime.Region(0, self.right.size()))

        diff = SublimergeDiffer().difference(text1, text2)

        differs = False

        if S.get('ignore_whitespace'):
            regexp = re.compile('(^\s+)|(\s+$)', re.MULTILINE)
            if re.sub(regexp, '', text1) != re.sub(regexp, '', text2):
                differs = True
        elif text1 != text2:
            differs = True

        if not differs:
            sublime.message_dialog('There is no difference between files')
            return

        diffView = SublimergeView(self.window, self.left, self.right, diff)
        self.left.erase_status('sublimerge-computing-diff')
    def getInfo():
        user_id = yield ('User ID', '')
        user_name = yield ('User Name', '')
        # server_address = yield ('Server Address', '')

        sublime.message_dialog('Your answers: ' + answers)

    # prompt_sequence(foo())

	def on_done(self, user_input):
		# sublime.status_message("User said: " + user_input)
		# this is a dialog box, with same message
		sublime.message_dialog("User ID: " + user_input + "is been stored! ")

	def run(self, edit):
		userfile = open('userInfo', 'w')
		# userfile.readline()
		if userfile.readline():
			# read the file
			for line in userfile:
				content += line

			# replace with the correct information
			jcontent = json.dump(content)

		# replace whole file content with user inputs
		prompt_sequence(getInfo())
		jcontent.userid = user_id
		jcontent.username = user_name
		# jcontent.serveraddr = server_address

		# fcontent = [{"userid":jcontent.userid}, {"username":jcontent.username}]
		userfile.write(jcontent)
Exemple #20
0
    def select(self, item):
        """Select action to perform."""

        if "action" in item:
            if item['action'] == "fold":
                self.folds += item["sequence"]
            elif item['action'] == "unfold":
                self.unfolds += item["sequence"]
            elif item['action'] == "mark":
                self.highlights += item['sequence']
            else:
                error("action %s is not a valid action" % item["action"])
        elif "highlight" in item and bool(item['highlight']):
            sublime.message_dialog(
                "RegReplace:\n\"on_save_sequence\" setting option '\"highlight\": true' is deprecated!"
                "\nPlease use '\"action\": \"mark\"'."
            )
            self.highlights += item['sequence']
        else:
            self.replacements.append(
                {
                    "sequence": item['sequence'],
                    "multi_pass": True if "multi_pass" in item and bool(item['multi_pass']) else False
                }
            )
def get_target_ros_path(user_query=True):
    ros_path_settings = sublime.load_settings(ROS_PATH_KEY)
    path = ros_path_settings.get("path", "")
    if path == "" and user_query:
        sublime.message_dialog(MESSAGE_NO_KEY)
        sublime.active_window().show_input_panel("Target ROS path:", "", save_ros_target_path, None, None)
    return path
    def show_results(self, search_value=''):
        # TODO: paging?
        if search_value:
            search_result = self.do_search(search_value)

        if search_result:

            text = ''
            while True:
                try:
                    hit = search_result.next()
                    if hit:
                        text += self.get_block(hit)
                except StopIteration:
                    break

            if text:
                self.view = sublime.active_window().new_file()
                # TODO: view set attrs in utils..
                syntax_file = mw.get_setting('syntax')
                self.view.set_syntax_file(syntax_file)
                self.view.set_name('Wiki search results: %s' % search_value)
                self.view.run_command(mw.cmd('insert_text'), {'position': 0, 'text': text})
            elif search_value:
                sublime.message_dialog('No results for: %s' % search_value)
Exemple #23
0
    def myret(key, value):
        if raw:
            return value
        if key == "adb_command" and type(value) == list:
            args = value[1:]
            value = value[0]
            msg = """The adb_command setting was changed from a list to a string, with the arguments in the separate setting \"adb_args\". \
 The setting for this view has been automatically converted, but you'll need to change the source of this setting for it to persist. The automatic conversion is now using these settings:

 "adb_command": "%s",
 "adb_args": %s,

 (Hint, this message is also printed in the python console for easy copy'n'paste)""" % (value, args)
            show = True
            try:
                show = not view.settings().get("adb_has_shown_message", False)
                view.settings().set("adb_has_shown_message", True)
            except:
                pass

            print(msg)

            if show:
                sublime.message_dialog(msg)
        elif key == "adb_args" and value == None:
            cmd = get_setting("adb_command", view, True)
            if type(cmd) == list:
                value = cmd[1:]
        if value == None:
            value = __adb_settings_defaults[key] or None

        return value
        def do_create(self):
            if len(self.w.folders()) == 0:
                message = "Ensime project cannot be created, because you either don't have a Sublime project "
                message += "or don't have any folders associated with your Sublime project."
                message += "\n\n"
                message += "To use Ensime you need to have an active non-empty project. "
                message += "Sublime will now try to initialize a project for you. "
                message += "\n\n"
                message += "You will be shown a dialog that will let you select a root folder for the project. "
                message += "After the root folder is selected, Sublime will create a configuration file in it. "
                message += "Do you wish to proceed?"
                if sublime.ok_cancel_dialog(message):
                    self.w.run_command("prompt_add_folder")
                    # if you don't do set_timeout, self.w.folders() won't be updated
                    sublime.set_timeout(self.post_prompt_add_folder, 0)
                    return

            if len(self.w.folders()) > 1:
                message = "A .ensime configuration file needs to be created in one of your project's folders."
                message += "\n\n"
                message += "Since you have multiple folders in the project, pick an appropriate folder in the dialog that will follow."
                sublime.message_dialog(message)

            if (len(self.w.folders())) == 1:
                self.folder_selected(0)
            else:
                self.w.show_quick_panel(self.w.folders(), self.folder_selected)
  def run(self, edit):
    super(RubocopAutoCorrectCommand, self).run(edit)

    cancel_op = self.user_wants_to_cancel()
    if cancel_op:
      return

    view = self.view
    path = view.file_name()
    quoted_file_path = FileTools.quote(path)

    if view.is_read_only():
      sublime.message_dialog('RuboCop: Unable to run auto correction on a read only buffer.')
      return

    # Inform user about unsaved contents of current buffer
    if view.is_dirty():
      warn_msg = 'RuboCop: The curent buffer is modified. Save the file and continue?'
      cancel_op = not sublime.ok_cancel_dialog(warn_msg)

    if cancel_op:
      return
    else:
      view.run_command('save')

    RubocopEventListener.instance().clear_marks(view)

    quoted_file_path = FileTools.quote(path)

    # Run rubocop with auto-correction
    self.runner.run(quoted_file_path, '-a')

    sublime.status_message('RuboCop: Auto correction done.')
    def run(self, edit, action='compact'):
        # Format all the code
        if re.match(r'.*\.css$', self.view.file_name())  :
            regx = '\}[ \t]*(?=[^\n]\S)|\}\s+(?=\n)'
            rules1 = self.view.find_all(regx)
            for x in rules1:
                self.view.replace(edit, self.view.find(regx, x.a), "}\n")
        # Format all the code End

        rule_starts = self.view.find_all('\{')
        rule_ends = self.view.find_all('\}')

        if len(rule_starts) != len(rule_ends):
            sublime.message_dialog("value not match!")
            return

        area = Ele.getArea(rule_starts, rule_ends)

        rules_regions = list()
        regions_to_process = list()

        selections = self.view.sel()
        if len(selections) == 1 and selections[0].empty():
            selections = [sublime.Region(0, self.view.size())]

        for i in range(len(area)):
            rule_region = area[i]
            rules_regions.append(rule_region)
            for sel in selections:
                if sel.intersects(rule_region):
                    regions_to_process.append(rule_region)
                    break

        regions_to_process.reverse()
        self.process_rules_regions(regions_to_process, action, edit)
Exemple #27
0
	def __init__(self, subl_args, curdir, sdk_path, private_key):
		super(CommandBuilder, self).__init__()
		self.curdir = curdir
		self.sdk_path = sdk_path
		self.private_key = private_key
		self.args = subl_args

		self.flags = subl_args["flags"] if "flags" in subl_args else []
		self.device = subl_args["device"] if "device" in subl_args and subl_args["device"] != "prompt" else False
		self.do = subl_args["do"] if "do" in subl_args else "build"

		if "sdk" in subl_args:
			target_sdks = SDK(sdk_path).targetSDKs()
			match = [x for x in target_sdks if subl_args["sdk"].replace(".x","") == ".".join(x.split(".")[:2])]
			if len(match):
				self.sdk = match[0]
			else:
				self.sdk = False
				sublime.message_dialog("unsupported SDK target: {}".format(subl_args["sdk"],))
		else:
			self.sdk = False

		# apps compile with monkeyc, barrels(modules) with barrelbuild
		# so we need to know which we are dealing with
		self.build_for = self.detect_app_vs_barrel()
Exemple #28
0
 def wrapper(self):
   try:
     return func(self, self.repository)
   except (NotAGitRepositoryError, NotAGithubRepositoryError):
     sublime.message_dialog("Github repository not found.")
   except (NoFileOpenError):
     sublime.message_dialog("Please open a file first.")
Exemple #29
0
 def run(self):
     listitems = []
     self.nodes = []
     labels = []
     label_ids = []
     regexs = [r"\$LOCALIZE\[([0-9].*?)\]", r"\$ADDON\[.*?([0-9].*?)\]", r"(?:label|property|altlabel|label2)>([0-9].*?)<"]
     view = self.window.active_view()
     path = view.file_name()
     for po_file in INFOS.po_files:
         labels += [s.msgid for s in po_file]
         label_ids += [s.msgctxt for s in po_file]
     # view.substr(sublime.Region(0, view.size()))
     with open(path, encoding="utf8") as f:
         for i, line in enumerate(f.readlines()):
             for regex in regexs:
                 for match in re.finditer(regex, line):
                     label_id = "#" + match.group(1)
                     if label_id in label_ids:
                         index = label_ids.index(label_id)
                         listitems.append("%s (%s)" % (labels[index], label_id))
                     node = {"file": path,
                             "line": i + 1}
                     self.nodes.append(node)
     if listitems:
         self.window.show_quick_panel(listitems, lambda s: self.on_done(s), selected_index=0, on_highlight=lambda s: self.show_preview(s))
     else:
         sublime.message_dialog("No references found")
def launch_simulator(file_name):
	QUICK_V3_ROOT = _find_environment_variable("QUICK_V3_ROOT")
	if QUICK_V3_ROOT == None:
		sublime.message_dialog("please set environment variable 'QUICK_V3_ROOT'")
		return

	WORKDIR = get_workdir(file_name)
	if WORKDIR == None: return

	BIN = ""
	ARG = " -workdir %s -search-path %s/quick" % (WORKDIR, QUICK_V3_ROOT)

	def _windows():
		os.system("taskkill /F /IM simulator.exe")
		return QUICK_V3_ROOT + "/tools/simulator/runtime/win32/simulator.exe"

	def _mac():
		os.system("ps -x|grep simulator|xargs kill -9")
		# os.system("open /Applications/Xcode.app")
#       QUICK_V3_ROOT + "/tools/simulator/runtime/mac/Simulator.app/Contents/MacOS/Simulator"
#       "/Users/liangxie/Desktop/work/qgl/frameworks/cocos2d-x/tools/simulator/runtime/mac/Simulator.app/Contents/MacOS/Simulator"
		return QUICK_V3_ROOT + "/tools/simulator/runtime/mac/Simulator.app/Contents/MacOS/Simulator"
#        return QUICK_V3_ROOT + "../Desktop/work/qgl/runtime/mac/qgl Mac.app/Contents/MacOS/qgl Mac"


	if _isWindows():
		BIN = _windows()
	if _is_mac(): 
		BIN = _mac()
	# if _isLinux(): _linux()

	sublime.set_timeout_async(lambda:os.system(BIN + ARG), 0)
Exemple #31
0
 def run(self, paths = []):
     sublime.message_dialog('AutoBackups: Thanks for your support ^_^')
     webbrowser.open_new_tab("https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&[email protected]&item_name=Donation to Sublime Text - AutoBackups&item_number=1&no_shipping=1")
Exemple #32
0
    def run(self, comando):
        global currentPath
        global puerto
        global usuario
        global nick
        global password
        global host
        global tipo
        file = os.path.basename(self.window.active_view().file_name())

        if comando == "put_sftp":
            self.window.run_command("save")
            return
        json_config = open(
            tmp_dir + diagonal + os.path.splitext(file)[0] + ".config", "r")
        json_file = json.loads(
            json_config.read())  #leemos el archivo de configuración
        json_config.close()

        tipo = json_file[0]["type"]
        if tipo != "sftp" and tipo != "ftp":
            sublime.message_dialog("Tipo de conexión invalida.")
            return
        host = json_file[0]["host"]
        usuario = json_file[0]["user"]
        nick = json_file[0]["nick"]
        if nick == "":
            sublime.message_dialog("Es necesario que coloques un Nick.")
            return
        password = json_file[0]["password"]
        puerto = json_file[0]["port"]
        currentPath = json_file[0]["remote_path"]

        if usuario == None or usuario == '':
            self.window.run_command(
                "progress_bar", {
                    "mensaje":
                    "No se ha definido el servidor host en el archivo de configuración"
                })
            return
        if host == None or host == '':
            self.window.run_command(
                "progress_bar", {
                    "mensaje":
                    "No se ha definido el servidor host en el archivo de configuración"
                })
            return
        if password == None or password == '':
            self.window.run_command(
                "progress_bar", {
                    "mensaje":
                    "No se ha definido el password en el archivo de configuración"
                })
            return

        if createPanelOutput == False:
            self.window.run_command("progress_bar",
                                    {"mensaje": "Conectando con el servidor"})
            self.window.run_command(
                "progress_bar",
                {"mensaje": "\nConectado en: " + host + " como: " + usuario})
        #Aqui listamos mostramos la lista de elementos comando ls
        self.window.run_command("get_sftp", {"file": file, "flag": True})
Exemple #33
0
    def run(self, edit, file, flag):
        global mydir
        global currentPath
        global createPanelOutput
        global host
        global password
        global usuario
        global nick
        global puerto
        global tipo
        global tmp_dir
        global diagonal
        mydir = sublime.packages_path() + "/User"

        if platform.system() == "Linux":
            diagonal = "/"
            tmp_dir = mydir + diagonal + "tmp_my_sftp"

        #flag sabemos si hay nombre de archivo o no

        if flag == True:
            ruta = file.replace(".sftp", "")
        else:
            ruta = file

        if os.path.dirname(ruta) == tmp_dir:
            #Es un archivo de la carpeta de temporales
            path_put = currentPath
            if flag == False:
                #mydir = os.path.dirname(os.path.abspath(__file__))
                file_path = open(os.path.splitext(ruta)[0] + ".path", "r")
                path_put = file_path.read()
                file_path.close()

                json_config = open(os.path.splitext(ruta)[0] + ".config", "r")
                json_file = json.loads(
                    json_config.read())  #leemos el archivo de configuración
                json_config.close()
                if host == '' or usuario == '' or password == '' or host != json_file[
                        0]["host"] or usuario != json_file[0][
                            "user"] or password != json_file[0]["password"]:
                    tipo = json_file[0]["type"]

                    if tipo != "sftp" and tipo != "ftp":
                        sublime.message_dialog("Tipo de conexión invalida.")
                        return
                    host = json_file[0]["host"]
                    usuario = json_file[0]["user"]
                    nick = json_file[0]["nick"]
                    password = json_file[0]["password"]
                    puerto = json_file[0]["port"]
                    currentPath = json_file[0]["remote_path"]

                    if usuario == None or usuario == '':
                        self.view.window().run_command(
                            "progress_bar", {
                                "mensaje":
                                "No se ha definido el servidor host en el archivo de configuración"
                            })
                        return
                    if host == None or host == '':
                        self.view.window().run_command(
                            "progress_bar", {
                                "mensaje":
                                "No se ha definido el servidor host en el archivo de configuración"
                            })
                        return
                    if password == None or password == '':
                        self.view.window().run_command(
                            "progress_bar", {
                                "mensaje":
                                "No se ha definido el password en el archivo de configuración"
                            })
                        return

                    if createPanelOutput == False:
                        self.view.window().run_command(
                            "progress_bar",
                            {"mensaje": "Conectando con el servidor"})
                        self.view.window().run_command(
                            "progress_bar", {
                                "mensaje":
                                "\nConectado en: " + host + " como: " + usuario
                            })
                    else:
                        self.view.window().run_command(
                            "progress_bar",
                            {"mensaje": "\nConectando con el servidor"})
                        self.view.window().run_command(
                            "progress_bar", {
                                "mensaje":
                                "\nConectado en: " + host + " como: " + usuario
                            })
                    #Aqui listamos mostramos la lista de elementos comando ls

            #Es un archivo de la carpeta de temporales
            ##############################################################################
            #salida = SFTP("cd " + currentPath + "\nls\n", tipo, "ls")
            salida = SFTP(
                "cd " + currentPath + "\nget " + os.path.basename(ruta) +
                ".sftp" + " " + tmp_dir + diagonal + os.path.basename(ruta) +
                ".sftp", tipo, "get")
            if os.path.exists(tmp_dir + diagonal + os.path.basename(ruta) +
                              ".sftp"):  #Validamos que exista el archivo
                nick_use = open(
                    tmp_dir + diagonal + os.path.basename(ruta) + ".sftp", "r")
                nick_current_use = nick_use.read()
                nick_use.close()
                if nick != nick_current_use and flag == False:
                    if not sublime.ok_cancel_dialog(
                            "El usuario " + nick_current_use +
                            " esta usando actualmente el archivo, Deseas subir tus cambios?."
                    ):
                        self.view.window().run_command(
                            "progress_bar", {"mensaje": "    Cancel."})
                        return
            nick_use = open(
                tmp_dir + diagonal + os.path.basename(ruta) + ".sftp", "w")
            nick_use.write(nick)
            nick_use.close()

            #---------------------------------HAY EVITAR UNA PETICIÓN DE MAS AQUÍ----------------------------------
            if flag == False:
                now = datetime.datetime.now()
                self.view.window().run_command(
                    "progress_bar", {
                        "mensaje":
                        "\n" + now.strftime("%H:%M:%S") + "->Subiendo: " +
                        ruta + " en " + path_put + os.path.basename(ruta),
                        "change":
                        False,
                        "loading":
                        True
                    })
                salida = SFTP(
                    "cd " + currentPath + "\n" + "put " + tmp_dir + diagonal +
                    os.path.basename(ruta) + ".sftp" + " " +
                    os.path.basename(ruta) + ".sftp" + "\nput " + ruta + " " +
                    path_put + os.path.basename(ruta), tipo, "put")
            else:
                salida = SFTP(
                    "cd " + currentPath + "\n" + "put " + tmp_dir + diagonal +
                    os.path.basename(ruta) + ".sftp" + " " + currentPath +
                    os.path.basename(ruta) + ".sftp", tipo, "put")

            if 'nick_current_use' in locals():
                if nick != nick_current_use:
                    os.remove(tmp_dir + diagonal + os.path.basename(ruta) +
                              ".sftp")

            #---------------------------------HAY EVITAR UNA PETICIÓN DE MAS AQUÍ----------------------------------
            if salida == "permission denied":
                self.view.window().run_command(
                    "progress_bar", {
                        "mensaje":
                        "    error\nNo tienes los permisos necesarios para escribir sobre el archivo",
                        "change": False,
                        "loading": True
                    })
                return
            if createPanelOutput == False:
                self.window.create_output_panel("progess_bar")
                createPanelOutput = True
            self.view.window().run_command("show_panel",
                                           {"panel": "output.progess_bar"})

            def show_progress_bar():
                show_progress_bar.message = "    success"
                show_progress_bar.change = True
                view = self.view.window().find_output_panel("progess_bar")
                if not flag:
                    view.run_command(
                        "my_insert_progress_bar", {
                            "message": show_progress_bar.message,
                            "change": show_progress_bar.change
                        })

            sublime.set_timeout_async(show_progress_bar, 1)
Exemple #34
0
    def run(self, edit, file, flag=False, lista=[]):
        global createPanelOutput
        #flag_edit = True
        now = datetime.datetime.now()
        self.view.window().run_command(
            "progress_bar", {
                "mensaje":
                "\n" + now.strftime("%H:%M:%S") + "->Descargando: " +
                currentPath + file + " en " + tmp_dir + diagonal + file,
                "change":
                False,
                "loading":
                True
            })

        if not os.path.exists(tmp_dir):
            os.makedirs(tmp_dir)  #Cramos la carpeta temporal
        ##############################################################################
        if "\n".join(lista).find(
                file + ".sftp") > 0:  #Validamos que exista el archivo
            salida = SFTP(
                "cd " + currentPath + "\nget " + file + ".sftp" + " " +
                tmp_dir + diagonal + file + ".sftp", tipo, "get")
            nick_use = open(tmp_dir + diagonal + file + ".sftp", "r")
            nick_current_use = nick_use.read()
            nick_use.close()
            if os.path.exists(tmp_dir + diagonal + file + ".sftp"):
                os.remove(tmp_dir + diagonal + file + ".sftp")

            if nick_current_use != nick:
                if not sublime.ok_cancel_dialog(
                        "El usuario " + nick_current_use +
                        " esta usando actualmente el archivo, Deseas continuar con la descarga?."
                ):
                    self.view.window().run_command("progress_bar",
                                                   {"mensaje": "    Cancel."})
                    return
                #flag_edit = False

        ##############################################################################
        if os.path.exists(tmp_dir + diagonal + file) and self.view.window(
        ).find_open_file(tmp_dir + diagonal + file) and flag == False:
            sublime.message_dialog(
                "Ya existe un archivo con el mismo nombre, cierre primero para poder continuar editando otro archivo con el mismo nombre."
            )
            return
        else:
            nick_use = open(tmp_dir + diagonal + file + ".sftp", "w")
            nick_use.write(nick)
            nick_use.close()
            #---------------------------------HAY EVITAR UNA PETICIÓN DE MAS AQUÍ----------------------------------
            salida = SFTP(
                "cd " + currentPath + "\nput " + tmp_dir + diagonal + file +
                ".sftp" + " " + os.path.basename(file) + ".sftp" + "\nget " +
                file + " " + tmp_dir + diagonal + file, tipo, "get")
            if os.path.exists(tmp_dir + diagonal + file + ".sftp"):
                os.remove(tmp_dir + diagonal + file + ".sftp")
            #---------------------------------HAY EVITAR UNA PETICIÓN DE MAS AQUÍ----------------------------------
            if salida == "permission denied":
                self.view.window().run_command("progress_bar", {
                    "mensaje":
                    "    error\nNo tiene los permisos necesarios."
                })
                return
        aux_path = open(
            tmp_dir + diagonal + os.path.splitext(file)[0] + ".path", "w")
        aux_path.write(currentPath)
        aux_path.close()

        aux_config = open(
            tmp_dir + diagonal + os.path.splitext(file)[0] + ".config", "w")
        aux_config.write("[{\n\t\"nick\" : \"" + nick +
                         "\",\n\t\"type\" : \"" + tipo +
                         "\",\n\t\"host\" : \"" + host +
                         "\",\n\t\"user\" : \"" + usuario +
                         "\",\n\t\"password\" : \"" + password +
                         "\",\n\t\"port\" : \"" + puerto +
                         "\",\n\t\"remote_path\" : \"" + currentPath +
                         "\"\n}]")
        aux_config.close()

        #------------------------------------------------------
        if createPanelOutput == False:
            self.window.create_output_panel("progess_bar")
            createPanelOutput = True
        self.view.window().run_command("show_panel",
                                       {"panel": "output.progess_bar"})

        def show_progress_bar():
            show_progress_bar.message = " "
            show_progress_bar.change = True
            vista = self.view.window().open_file(tmp_dir + diagonal + file)
            while vista.is_loading():
                view = self.view.window().find_output_panel("progess_bar")
                view.run_command(
                    "my_insert_progress_bar", {
                        "message": show_progress_bar.message,
                        "change": show_progress_bar.change
                    })

        sublime.set_timeout_async(show_progress_bar, 1)
Exemple #35
0
    def on_done(self, index):
        global mydir
        global currentPath
        global puerto
        global usuario
        global nick
        global password
        global host
        global tipo

        if index == 0:
            self.window.run_command('new_server')
        elif index > 0:
            json_config = open(mydir + diagonal + listServers[index] + ".json",
                               "r")
            json_file = json.loads(
                json_config.read())  #leemos el archivo de configuración
            json_config.close()

            tipo = json_file[0]["type"]
            if tipo != "sftp" and tipo != "ftp":
                sublime.message_dialog("Tipo de conexión invalidaaaa.")
                return

            if (currentPath
                    == "") or (host != "" and host != json_file[0]["host"]
                               and usuario != ""
                               and usuario != json_file[0]["user"]):
                currentPath = json_file[0]["remote_path"]

            host = json_file[0]["host"]
            usuario = json_file[0]["user"]
            nick = json_file[0]["nick"]
            if nick == "":
                sublime.message_dialog("Es necesario que coloques un Nick.")
                return
            password = json_file[0]["password"]
            puerto = json_file[0]["port"]

            if usuario == None or usuario == '':
                self.window.run_command(
                    "progress_bar", {
                        "mensaje":
                        "No se ha definido el servidor host en el archivo de configuración"
                    })
                return
            if host == None or host == '':
                self.window.run_command(
                    "progress_bar", {
                        "mensaje":
                        "No se ha definido el servidor host en el archivo de configuración"
                    })
                return
            if password == None or password == '':
                self.window.run_command(
                    "progress_bar", {
                        "mensaje":
                        "No se ha definido el password en el archivo de configuración"
                    })
                return

            if createPanelOutput == False:
                self.window.run_command(
                    "progress_bar", {"mensaje": "Conectando con el servidor"})
                self.window.run_command("progress_bar", {
                    "mensaje":
                    "\nConectado en: " + host + " como: " + usuario
                })
            #Aqui listamos mostramos la lista de elementos comando ls
            self.window.run_command(
                "progress_bar",
                {"mensaje": "\nListando el directorio: " + currentPath})
            salida = SFTP("cd " + currentPath + "\nls\nbye\n", tipo, "ls")
            if salida == False:
                self.window.run_command(
                    "progress_bar", {
                        "mensaje":
                        "    error\nImposible conectar con el servidor por el momento."
                    })
                return
            self.window.run_command("show_ls", {"args": salida})
Exemple #36
0
def md(*t, **kwargs):
    sublime.message_dialog(kwargs.get('sep', '\n').join([str(el) for el in t]))
Exemple #37
0
 def show_in_dialog(self, message_str):
     sublime.message_dialog(xstr(message_str))
Exemple #38
0
    def selectFunction(callback):
        if len(ST.functions) == 0:
            sublime.message_dialog('Your database has no functions.')
            return

        Window().show_quick_panel(ST.functions, callback)
Exemple #39
0
 def run(self):
     for filepath in sublime.find_resources("*.javatar-imports"):
         get_action().add_action(
             "javatar.command.utils.convert.run",
             "Converting imports \"" + get_path("name", filepath) + "\"")
         packages_file = {
             "name": get_path("name", filepath),
             "packages": {}
         }
         imports_file = sublime.decode_value(
             sublime.load_resource(filepath))
         total_package = 0
         total_class = 0
         for imports in imports_file:
             if "package" in imports:
                 total_package += 1
                 package = imports["package"]
                 packages_file["packages"][package] = {}
                 if "default" in imports:
                     packages_file["packages"][package][
                         "default"] = imports["default"]
                 if "interface" in imports:
                     packages_file["packages"][package]["interface"] = []
                     total_class += len(imports["interface"])
                     for clss in imports["interface"]:
                         packages_file["packages"][package][
                             "interface"].append({
                                 "name": clss,
                                 "fields": [],
                                 "methods:": []
                             })
                 if "class" in imports:
                     packages_file["packages"][package]["class"] = []
                     total_class += len(imports["class"])
                     for clss in imports["class"]:
                         packages_file["packages"][package]["class"].append(
                             {
                                 "name": clss,
                                 "fields": [],
                                 "methods:": []
                             })
                 if "enum" in imports:
                     packages_file["packages"][package]["enum"] = []
                     total_class += len(imports["enum"])
                     for clss in imports["enum"]:
                         packages_file["packages"][package]["enum"].append({
                             "name":
                             clss,
                             "fields": [],
                             "methods:": []
                         })
                 if "exception" in imports:
                     packages_file["packages"][package]["exception"] = []
                     total_class += len(imports["exception"])
                     for clss in imports["exception"]:
                         packages_file["packages"][package][
                             "exception"].append({
                                 "name": clss,
                                 "fields": [],
                                 "methods:": []
                             })
                 if "error" in imports:
                     packages_file["packages"][package]["error"] = []
                     total_class += len(imports["error"])
                     for clss in imports["error"]:
                         packages_file["packages"][package]["error"].append(
                             {
                                 "name": clss,
                                 "fields": [],
                                 "methods:": []
                             })
                 if "annotation" in imports:
                     packages_file["packages"][package]["annotation"] = []
                     total_class += len(imports["annotation"])
                     for clss in imports["annotation"]:
                         packages_file["packages"][package][
                             "annotation"].append({
                                 "name": clss,
                                 "fields": [],
                                 "methods:": []
                             })
                 if "type" in imports:
                     packages_file["packages"][package]["type"] = []
                     total_class += len(imports["type"])
                     for clss in imports["type"]:
                         packages_file["packages"][package]["type"].append({
                             "name":
                             clss,
                             "fields": [],
                             "methods:": []
                         })
         with open(
                 get_path(
                     "join", get_path("parent", sublime.packages_path()),
                     filepath.replace(".javatar-imports",
                                      "-converted.javatar-packages")),
                 "w") as filew:
             print(sublime.encode_value(packages_file, True), file=filew)
             sublime.message_dialog("Conversion Done\nTotal Packages: " +
                                    str(total_package) +
                                    "\nTotal Classes: " + str(total_class))
Exemple #40
0
 def run():
     sublime.message_dialog('Using {0} {1}'.format(__package__,
                                                   __version__))
Exemple #41
0
def md(*t, **kwargs):
	t = kwargs.get('sep', ' ').join([str(el) for el in t])
	sublime.message_dialog(t)
Exemple #42
0
    def selectTable(callback):
        if len(ST.tables) == 0:
            sublime.message_dialog('Your database has no tables.')
            return

        Window().show_quick_panel(ST.tables, callback)
Exemple #43
0
 def run(self):
     sublime.message_dialog('You have LaTeXing %s' % LTX_VERSION)
    def run(self, command, **args):
        # Allow only known commands
        if command not in DebuggerModel.COMMANDS:
            sublime.message_dialog("Unknown command: " + command)
            return
        # Allow only start command when inactive
        if not self.debugger and command not in DebuggerModel.STARTERS_COMMANDS:
            return

        # Cursor movement commands
        if command == DebuggerModel.COMMAND_JUMP:
            current_line = ViewHelper.get_current_cursor(
                self.window, self.debugger_model.get_current_file())

            if current_line:
                self.clear_cursor()
                self.debugger.run_command(command, str(current_line + 1))
                self.debugger.run_command(DebuggerModel.COMMAND_GET_LOCATION)
        elif command == DebuggerModel.COMMAND_GO_TO:
            file_name = self.debugger_model.get_current_file()
            current_line = ViewHelper.get_current_cursor(
                self.window, file_name)

            if current_line:
                self.clear_cursor()
                self.debugger.run_command(
                    DebuggerModel.COMMAND_SET_BREAKPOINT,
                    file_name + ":" + str(current_line + 1))
                self.debugger.run_command(DebuggerModel.COMMAND_CONTINUTE)
                self.register_breakpoints()
        elif command in DebuggerModel.MOVEMENT_COMMANDS:
            self.clear_cursor()
            self.debugger.run_command(command, **args)
            self.debugger.run_command(DebuggerModel.COMMAND_GET_LOCATION)
        # Input commands
        elif command == DebuggerModel.COMMAND_DEBUG_LAYOUT:
            self.show_debugger_layout()
        elif command == DebuggerModel.COMMAND_RESET_LAYOUT:
            if not self.debugger_model:
                self.debugger_model = DebuggerModel(self.debugger)

            if not self.debug_views:
                self.debug_views = dict([
                    (key, None)
                    for key in self.debugger_model.get_data().keys()
                ])

            ViewHelper.reset_debug_layout(self.window, self.debug_views)
        elif command == DebuggerModel.COMMAND_SEND_INPUT:
            self.window.show_input_panel(
                "Enter input", '',
                lambda input_line: self.on_input_entered(input_line), None,
                None)
        elif command == DebuggerModel.COMMAND_GET_EXPRESSION:
            self.window.show_input_panel(
                "Enter expression", '',
                lambda exp: self.on_expression_entered(exp), None, None)
        elif command == DebuggerModel.COMMAND_ADD_WATCH:
            self.window.show_input_panel(
                "Enter watch expression", '',
                lambda exp: self.on_watch_entered(exp), None, None)
        # Start command
        elif command == DebuggerModel.COMMAND_START_RAILS:
            settings = sublime.load_settings('Ruby Debugger.sublime-settings')

            if PathHelper.file_exists(settings.get("rails_executable_path"),
                                      self.window):
                self.start_command(
                    settings.get("rails_executable_path") + " s", True)
            elif PathHelper.file_exists("script/rails", self.window):
                self.start_command("script/rails s", True)
            elif PathHelper.file_exists("bin/rails",
                                        self.window):  # Rails 4 support
                self.start_command("bin/rails s", True)
            else:
                sublime.message_dialog(
                    "Cannot find file. Are you sure you're in a rails project?"
                )
        elif command == DebuggerModel.COMMAND_START_CURRENT_FILE:
            self.start_command(self.window.active_view().file_name())
        elif command == DebuggerModel.COMMAND_START:
            self.window.show_input_panel(
                "Enter file name", '',
                lambda file_name: self.start_command(file_name), None, None)
        # Register breakpoints command
        elif command == DebuggerModel.COMMAND_SET_BREAKPOINT:
            self.register_breakpoints()
        # All othe commands
        else:
            self.debugger.run_command(command)
Exemple #45
0
    def run(self, edit, transformation):

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

        # pandoc executable
        pandoc = _find_binary('pandoc', _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'])

        # 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
                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)
        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'))
            view.set_syntax_file(transformation['syntax_file'])
Exemple #46
0
	def runInternal(self, console=True):
		out = self.run(self.command, console)
		sublime.message_dialog(out.decode("utf-8"))
		return out.decode("utf-8")
Exemple #47
0
 def run(self, paths=[]):
     sublime.message_dialog('AutoBackups: Thanks for your support ^_^')
     browser = settings.get("default_browser", "")
     AutoBackupsOpenInBrowserThread('', '').try_open(
         "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=MVCBM7M2RCEX6&lc=US&item_name=Support%20our%20open%2dsource%20initiatives&item_number=donation&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted",
         browser)
Exemple #48
0
 def _handle_error(self, command: str, error: Dict[str, Any]) -> None:
     msg = "command {} failed. Reason: {}".format(command, error.get("message", "none provided by server :("))
     sublime.message_dialog(msg)
Exemple #49
0
    def generate_colour_scheme(self, view, generate=True):
        # make sure we have hex AND we're >= ST3 (load_resource doesn't work in ST2)
        colour_removed = sbs_settings().get('remove_colour', 'invalid.illegal')
        colour_added = sbs_settings().get('add_colour', 'string')
        colour_modified_deletion = sbs_settings().get(
            'modified_colour_deletion', 'support.class')
        colour_modified_addition = sbs_settings().get(
            'modified_colour_addition', 'support.class')
        colour_unmodified_deletion = sbs_settings().get(
            'unmodified_colour_deletion', 'invalid.illegal')
        colour_unmodified_addition = sbs_settings().get(
            'unmodified_colour_addition', 'string')
        colour_text = sbs_settings().get('text_colour', '')

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

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

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

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

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

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

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

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

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

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

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

            # save new theme
            try:
                with open(abs_theme_file, 'w', encoding='utf-8') as f:
                    f.write(data)
            except:
                sublime.message_dialog(
                    'Could not write theme file.\nPlease ensure that your Sublime config directory is writeable and restart Sublime.\n\nFull path:\n'
                    + abs_theme_file)

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

        # set view settings to use new theme
        view.settings().set('color_scheme', self.last_theme_file)
        return colourStrings
Exemple #50
0
    def check_config(self):
        """Check the configuration looks fine
        """

        if self.interpreter.network is None:
            self.interpreter.network = 'forwarded'

        network = self.interpreter.network
        if network == 'public' and self.interpreter.dev is None:
            self.error = (
                'network is configured as public but no device is specified')
            self.tip = ('Specify a network device using `dev=<net_iface> or '
                        'use a different network topology')
            return False

        if network == 'private' and self.interpreter.address is None:
            self.error = ('vagrant network configured as private but '
                          'no address has been supplied')
            self.tip = (
                'Add the address parameter to your vagrant URI or change the '
                'network parameter to forwarded')
            return False

        if not self._check_status():

            self.error = 'vagrant machine {} is not running'.format(
                self.interpreter.machine)
            self.tip = 'Start the vagrant machine'

            start_now = sublime.ok_cancel_dialog(
                '{} virtual machine is not running, do you want to start it '
                'now (it may take a while)?'.format(self.interpreter.machine),
                'Start Now')
            if start_now:
                sublime.active_window().run_command('show_panel', {
                    'panel': 'console',
                    'toggle': False
                })
                try:
                    messages = {
                        'start':
                        'Starting {} VM, please wait...'.format(
                            self.interpreter.machine),
                        'end':
                        'Done!',
                        'fail':
                        'Machine {} could not be started'.format(
                            self.interpreter.machine),
                        'timeout':
                        ''
                    }
                    pbar = ProgressBar(messages)
                    VagrantStartMachine(self.interpreter.machine,
                                        self.interpreter.vagrant_root)
                except RuntimeError as error:
                    pbar.terminate(status=pbar.Status.FAILURE)
                    sublime.error_message(str(error))
                    return False
                else:
                    pbar.terminate()
                    sublime.message_dialog('Machine {} started.'.format(
                        self.interpreter.machine))
                    return self.check()

            return False

        return True
Exemple #51
0
 def run():
     sublime.message_dialog('Using SQLTools ' + STM.VERSION)
Exemple #52
0
    def compare_views(self, view1, view2):
        view1_contents = self.get_view_contents(view1)
        view2_contents = self.get_view_contents(view2)

        linesA = view1_contents.splitlines(False)
        linesB = view2_contents.splitlines(False)

        if sbs_settings().has('ignore_pattern'):
            ignore_pattern = sbs_settings().get('ignore_pattern')
            pattern = re.compile(ignore_pattern, re.MULTILINE)
            view1_contents = pattern.sub('', view1_contents)
            view2_contents = pattern.sub('', view2_contents)

        if sbs_settings().get('ignore_whitespace', False):
            view1_contents = re.sub(r'[ \t]', '', view1_contents)
            view2_contents = re.sub(r'[ \t]', '', view2_contents)

        if sbs_settings().get('ignore_case', False):
            view1_contents = view1_contents.lower()
            view2_contents = view2_contents.lower()

        diffLinesA = view1_contents.splitlines(False)
        diffLinesB = view2_contents.splitlines(False)

        bufferA = []
        bufferB = []

        highlightA = []
        highlightB = []

        subHighlightA = []
        subHighlightB = []

        diff = difflib.ndiff(diffLinesA, diffLinesB, charjunk=None)

        hasDiffA = False
        hasDiffB = False
        intraLineA = ''
        intraLineB = ''
        hasIntraline = False
        '''
		An "intraline" difference is always a '-' line, possibly followed by
		'?' line, and immediately followed by a '+' line; the next line after
		that '+' might be another '?' line as well, or not. This is all
		dependent on whether the new file line (view2's) added, removed, or
		just changed characters relative to the original. If the new file line
		has more characters but no other differences, then the diff sequence
		would be '-', '+', '?'; if the new file has fewer characters but no
		other differences, the sequence will be '-', '?', '+'; if the new file
		has other character differences relative to the original, then the
		sequence will be '-', '?', '+', '?'.
		'''

        lineNum = 0
        lineA = 0
        lineB = 0
        for line in diff:
            lineNum += 1
            code = line[:2]

            if code == '- ':
                bufferA.append(linesA[lineA])
                bufferB.append('')
                highlightA.append(lineNum - 1)
                intraLineA = linesA[lineA]
                hasDiffA = True
                hasDiffB = False
                hasIntraline = False
                lineA += 1
            elif code == '+ ':
                bufferA.append('')
                bufferB.append(linesB[lineB])
                highlightB.append(lineNum - 1)
                intraLineB = linesB[lineB]
                hasDiffB = True
                lineB += 1
            elif code == '  ':
                bufferA.append(linesA[lineA])
                bufferB.append(linesB[lineB])
                hasDiffA = False
                hasDiffB = False
                hasIntraline = False
                lineA += 1
                lineB += 1
            elif code == '? ':
                lineNum -= 1
                hasIntraline = True
            else:
                lineNum -= 1

            if hasIntraline and hasDiffA and hasDiffB:
                if sbs_settings().get('enable_intraline', True):
                    # fixup line alignment
                    assert bufferA[-1] == ''
                    assert bufferB[-2] == ''
                    bufferB[-1] = bufferB.pop()
                    bufferA.pop()
                    highlightB[-1] = highlightA[-1]
                    lineNum -= 1
                    assert highlightB[-1] == lineNum - 1

                    s = difflib.SequenceMatcher(None, intraLineA, intraLineB)
                    for tag, i1, i2, j1, j2 in s.get_opcodes():
                        if tag != 'equal':  # == replace
                            if sbs_settings().get('intraline_emptyspace',
                                                  False):
                                if tag == 'insert':
                                    i2 += j2 - j1
                                if tag == 'delete':
                                    j2 += i2 - i1

                            subHighlightA.append([lineNum - 1, i1, i2])
                            subHighlightB.append([lineNum - 1, j1, j2])
                hasDiffA = False
                hasDiffB = False
                hasIntraline = False

        window = sublime.active_window()

        window.focus_view(view1)
        window.run_command('erase_view')
        window.run_command('insert_view', {'string': '\n'.join(bufferA)})

        window.focus_view(view2)
        window.run_command('erase_view')
        window.run_command('insert_view', {'string': '\n'.join(bufferB)})

        self.highlight_lines(view1, highlightA, subHighlightA, 'A')
        self.highlight_lines(view2, highlightB, subHighlightB, 'B')

        intraDiff = ''
        if sbs_settings().get('enable_intraline', True):
            self.sub_highlight_lines(view1, subHighlightA, 'A')
            self.sub_highlight_lines(view2, subHighlightB, 'B')

            numIntra = len(subHighlightB)
            intraDiff = str(numIntra) + ' intra-line modifications\n'

        if sbs_settings().get('line_count_popup', False):
            numDiffs = len(highlightA) + len(highlightB)
            sublime.message_dialog(intraDiff + str(len(highlightA)) +
                                   ' lines removed, ' + str(len(highlightB)) +
                                   ' lines added\n' + str(numDiffs) +
                                   ' line differences total')
Exemple #53
0
    def page_open(self, title):
        self.title = title

        if self.new_tab:
            view = sublime.active_window().new_file()
            utils.props.set_view_setting(view, 'site', self.site_active)
        else:
            view = self.view

        page = utils.api.call('get_page', title=self.title)
        utils.props.set_view_setting(
            view, 'section', self.section if self.section is not None else 0)

        if utils.api.page_can_edit(page):
            # can read and edit
            utils.props.set_view_setting(view, 'page_revision',
                                         utils.api.page_attr(page, 'revision'))
        elif not utils.api.page_can_read(page):
            # can not read and edit
            sublime.message_dialog(utils.api.PAGE_CANNOT_READ_MESSAGE)
            view.close()
            return
        elif not sublime.ok_cancel_dialog(
                '{} Click OK button to view its source.'.format(
                    utils.api.PAGE_CANNOT_EDIT_MESSAGE)):
            # can not edit, but can read, but not want
            view.close()
            return

        text = utils.api.page_get_text(page, self.section)
        page_namespace = utils.api.page_attr(page, 'namespace')

        if not text:
            utils.error_message(
                'Page [[{}]] does not exist. You can create it..'.format(
                    self.title))
            text = utils.comment(
                'New wiki page: Remove this with text of the new page',
                page_name=self.title,
                page_namespace=page_namespace)
            text = self.render_page_template(site_name=utils.get_view_site(),
                                             page_name=self.title,
                                             page_namespace=page_namespace,
                                             page_text=text)

        view.run_command(utils.cmd('insert_text'), {
            'position': 0,
            'text': text,
            'with_erase': True
        })

        if utils.props.get_site_setting(self.site_active, 'show_red_links'):
            utils.show_red_links(view, page)
        utils.status_message(
            'Page [[{}]] was opened successfully from "{}".'.format(
                self.title, utils.get_view_site()),
            replace_patterns=['[', ']'])
        utils.set_syntax(self.title, page_namespace)
        utils.props.set_view_setting(view, 'is_here', True)
        utils.props.set_view_setting(
            view, 'wiki_instead_editor',
            utils.props.get_setting('wiki_instead_editor'))
        view.set_name(self.title)
        view.set_scratch(True)
        # own is_changed flag instead of is_dirty for possib. to reset..
        utils.props.set_view_setting(view, 'is_changed', False)

        try:
            self.get_notifications()
        except Exception as e:
            utils.error_message('{} notifications exception: {}'.format(
                utils.props.PM, e))
Exemple #54
0
 def token_input_done(self, text):
     if not text:
         self.get_token(False)
         sublime.message_dialog("Please input your Access TOKEN!")
     else:
         self.set_token(text)
    def loadIos(self, srcPath):
        logging.info('loadIos: current dir is ')
        if 'windows' in platform.system().lower():
            if not os.path.exists(
                    os.path.join(self.__curDir, 'tools', 'jre', 'bin')):
                logging.info('loadIos: cannot find load.conf')
                sublime.error_message(u'缺少JRE环境')
                return
        else:
            (rtnCode, stdout,
             stderr) = runShellCommand('java -version', self.__cmdLogType)
            outputMsg = stdout + stderr
            if 'version' not in outputMsg:
                sublime.error_message(u'缺少JRE环境')
                return
        if not os.path.exists(
                os.path.join(self.__curDir, 'appLoader', 'apicloud-loader-ios',
                             'load.conf')) or not os.path.exists(
                                 os.path.join(self.__curDir, 'appLoader',
                                              'apicloud-loader', 'load.apk')):
            logging.info('loadIos: cannot find load.conf')
            sublime.error_message(u'真机同步缺少文件')
            return
        appId = self.getAppId(srcPath)
        self.getIosLoaderType(appId)
        logging.info('loadIos: appId is ' + str(appId))
        if -1 == appId:
            sublime.error_message(u'请确保目录正确')
            return

        if 'windows' in platform.system().lower():
            javaCmd = os.path.join(self.__curDir, 'tools', 'jre', 'bin',
                                   'java')
        else:
            javaCmd = 'java'

        fulldirname = os.path.abspath(srcPath)
        tmpPathName = 'tmp-apicloud-folder'
        tmpPath = os.path.join(os.path.dirname(srcPath), tmpPathName)
        # force delete .git which is read only
        for (p, d, f) in os.walk(tmpPath):
            if p.find('.git') > 0:
                if 'windows' in platform.system().lower():
                    os.popen('rd /s /q %s' % p)
                elif 'darwin' in platform.system().lower():
                    os.popen('rm -rf %s' % p)
        if os.path.exists(tmpPath):
            self.CleanDir(tmpPath)
            os.rmdir(tmpPath)
        shutil.copytree(srcPath,
                        tmpPath,
                        ignore=shutil.ignore_patterns(*self.__ignore))

        jarFile = os.path.join(self.__curDir, 'tools', 'syncapp.jar')
        iosLoaderPath = os.path.join(self.__curDir, 'appLoader',
                                     self.__loaderName)
        versionFile = os.path.join(iosLoaderPath, 'load.conf')
        iosLoaderFile = os.path.join(iosLoaderPath, 'load.ipa')

        iosSyncCmd = '"' + javaCmd + '" -jar "' + jarFile + '" "' + srcPath + \
            '" "' + iosLoaderPath + '" "' + iosLoaderFile + '" "' + versionFile + '"'
        logging.info('loadIos: cmd is' + iosSyncCmd)
        (rtnCode, stdout, stderr) = runShellCommand(iosSyncCmd,
                                                    self.__cmdLogType)
        outputMsg = stdout + stderr
        logging.info('loadIos: outputMsg is ' + outputMsg)
        self.CleanDir(tmpPath)
        os.rmdir(tmpPath)

        if 'No iOS device attached' in outputMsg:
            sublime.error_message(u'未发现连接的设备')
            logging.info('loadIos: no ios device found !')
        elif 'error' in outputMsg or 'failed' in outputMsg:
            logging.info('loadIos: failed to sync ios')
            sublime.error_message(u'IOS真机同步失败')
        else:
            logging.info('loadIos: ios sync success.')
            sublime.message_dialog(u'IOS真机同步完成')
def md(*t, **kwargs):
    sublime.message_dialog(kwargs.get("sep", "\n").join([str(el) for el in t]))
Exemple #57
0
def dofmt(eself, eview, sgter=None, src=None, force=False):
    if int(sublime.version()) < 3000:
        print_debug("phpfmt: ST2 not supported")
        return False

    self = eself
    view = eview
    s = sublime.load_settings('phpfmt.sublime-settings')
    additional_extensions = s.get("additional_extensions", [])

    uri = view.file_name()
    dirnm, sfn = os.path.split(uri)
    ext = os.path.splitext(uri)[1][1:]
    if force is False and "php" != ext and not ext in additional_extensions:
        print_debug("phpfmt: not a PHP file")
        return False

    php_bin = getSetting(view, s, "php_bin", "php")
    engine = getSetting(view, s, "engine", "fmt.phar")
    formatter_path = os.path.join(dirname(realpath(sublime.packages_path())),
                                  "Packages", "phpfmt", engine)

    if not os.path.isfile(formatter_path):
        sublime.message_dialog("engine file is missing: " + formatter_path)
        return

    if engine != "fmt.phar":

        def localFmt():
            options = getSetting(view, s, "options", [])
            cmd_fmt = [php_bin, formatter_path] + options + [uri]
            print_debug(cmd_fmt)
            p = subprocess.Popen(cmd_fmt,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 cwd=dirnm,
                                 shell=False)
            res, err = p.communicate()

            print_debug("p:\n", p.returncode)
            print_debug("out:\n", res.decode('utf-8'))
            print_debug("err:\n", err.decode('utf-8'))
            sublime.set_timeout(revert_active_window, 2000)

        sublime.set_timeout(localFmt, 100)
        return False

    indent_with_space = getSetting(view, s, "indent_with_space", False)
    debug = getSetting(view, s, "debug", False)
    ignore_list = getSetting(view, s, "ignore_list", "")
    passes = getSetting(view, s, "passes", [])
    excludes = getSetting(view, s, "excludes", [])

    config_file = os.path.join(dirname(realpath(sublime.packages_path())),
                               "Packages", "phpfmt", "php.tools.ini")

    if force is False and "php" != ext and not ext in additional_extensions:
        print_debug("phpfmt: not a PHP file")
        return False

    if "" != ignore_list:
        if type(ignore_list) is not list:
            ignore_list = ignore_list.split(" ")
        for v in ignore_list:
            pos = uri.find(v)
            if -1 != pos and v != "":
                print_debug("phpfmt: skipping file")
                return False

    if not os.path.isfile(php_bin) and not php_bin == "php":
        print_debug("Can't find PHP binary file at " + php_bin)
        sublime.error_message("Can't find PHP binary file at " + php_bin)

    cmd_ver = [php_bin, '-v']
    p = subprocess.Popen(cmd_ver,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         shell=False)
    res, err = p.communicate()
    print_debug("phpfmt (php_ver) cmd:\n", cmd_ver)
    print_debug("phpfmt (php_ver) out:\n", res.decode('utf-8'))
    print_debug("phpfmt (php_ver) err:\n", err.decode('utf-8'))
    if ('PHP 5.3' in res.decode('utf-8') or 'PHP 5.3' in err.decode('utf-8')
            or 'PHP 5.4' in res.decode('utf-8')
            or 'PHP 5.4' in err.decode('utf-8')
            or 'PHP 5.5' in res.decode('utf-8')
            or 'PHP 5.5' in err.decode('utf-8')
            or 'PHP 5.6' in res.decode('utf-8')
            or 'PHP 5.6' in err.decode('utf-8')):
        s = debugEnvironment(php_bin, formatter_path)
        sublime.message_dialog(
            'Warning.\nPHP 7.0 or newer is required.\nPlease, upgrade your local PHP installation.\nDebug information:'
            + s)
        return False

    s = debugEnvironment(php_bin, formatter_path)
    print_debug(s)

    lintret = 1
    if "AutoSemicolon" in passes:
        lintret = 0
    else:
        cmd_lint = [php_bin, "-ddisplay_errors=1", "-l"]
        if src is None:
            cmd_lint.append(uri)
            p = subprocess.Popen(cmd_lint,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 cwd=dirnm,
                                 shell=False)
        else:
            p = subprocess.Popen(cmd_lint,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=False)
            p.stdin.write(src.encode('utf-8'))

        lint_out, lint_err = p.communicate()
        lintret = p.returncode

    if (lintret == 0):
        cmd_fmt = [php_bin]

        if not debug:
            cmd_fmt.append("-ddisplay_errors=stderr")

        cmd_fmt.append(formatter_path)
        cmd_fmt.append("--config=" + config_file)

        if indent_with_space is True:
            cmd_fmt.append("--indent_with_space")
        elif indent_with_space > 0:
            cmd_fmt.append("--indent_with_space=" + str(indent_with_space))

        if len(passes) > 0:
            cmd_fmt.append("--passes=" + ','.join(passes))

        if len(excludes) > 0:
            cmd_fmt.append("--exclude=" + ','.join(excludes))

        if debug:
            cmd_fmt.append("-v")

        if src is None:
            cmd_fmt.append(uri)
        else:
            cmd_fmt.append("-")

        print_debug("cmd_fmt: ", cmd_fmt)

        if src is None:
            p = subprocess.Popen(cmd_fmt,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 cwd=dirnm,
                                 shell=False)
        else:
            p = subprocess.Popen(cmd_fmt,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=False)

        if src is not None:
            p.stdin.write(src.encode('utf-8'))

        res, err = p.communicate()

        print_debug("p:\n", p.returncode)
        print_debug("err:\n", err.decode('utf-8'))

        if p.returncode != 0:
            return ''

        return res.decode('utf-8')
    else:
        sublime.status_message("phpfmt: format failed - syntax errors found")
        print_debug("lint error: ", lint_out)
Exemple #58
0
 def run(sef):
     sublime.message_dialog(stt_about_message)
Exemple #59
0
    def compare_views(self, view1, view2):
        view1_contents = self.get_view_contents(view1)
        view2_contents = self.get_view_contents(view2)

        linesA = view1_contents.splitlines(False)
        linesB = view2_contents.splitlines(False)

        bufferA = []
        bufferB = []

        highlightA = []
        highlightB = []

        subHighlightA = []
        subHighlightB = []

        diff = difflib.ndiff(linesA, linesB, charjunk=None)

        lastB = False
        intraLineA = ''
        intraLineB = ''

        lineNum = 0
        for line in diff:
            lineNum += 1

            code = line[:2]
            text = line[2:]

            if code == '- ':
                bufferA.append(text)
                bufferB.append('')
                highlightA.append(lineNum - 1)
                intraLineA = text
                lastB = False
            elif code == '+ ':
                bufferA.append('')
                bufferB.append(text)
                highlightB.append(lineNum - 1)
                intraLineB = text
                lastB = True
            elif code == '  ':
                bufferA.append(text)
                bufferB.append(text)
                lastB = False
            elif code == '? ' and lastB == True:
                lineNum -= 1

                if self.settings().get('enable_intraline', True):
                    s = difflib.SequenceMatcher(None, intraLineA, intraLineB)
                    for tag, i1, i2, j1, j2 in s.get_opcodes():
                        if tag != 'equal':  # == replace
                            lnA = lineNum - 2
                            lnB = lineNum - 1

                            if self.settings().get('full_intraline_highlights',
                                                   False):
                                if tag == 'insert':
                                    i2 += j2 - j1
                                if tag == 'delete':
                                    j2 += i2 - i1

                            subHighlightA.append([lnA, i1, i2])
                            subHighlightB.append([lnB, j1, j2])
                lastB = False
            else:
                lineNum -= 1

        window = sublime.active_window()

        window.focus_view(view1)
        window.run_command('erase_view')
        window.run_command('insert_view', {'string': '\n'.join(bufferA)})

        window.focus_view(view2)
        window.run_command('erase_view')
        window.run_command('insert_view', {'string': '\n'.join(bufferB)})

        self.highlight_lines(view1, highlightA, subHighlightA, 'A')
        self.highlight_lines(view2, highlightB, subHighlightB, 'B')

        intraDiff = ''
        if self.settings().get('enable_intraline', True):
            self.sub_highlight_lines(view1, subHighlightA, 'A')
            self.sub_highlight_lines(view2, subHighlightB, 'B')

            numIntra = len(subHighlightA) + len(subHighlightB)
            intraDiff = str(numIntra) + ' intra-line modifications\n'

        if self.settings().get('line_count_popup', False):
            numDiffs = len(highlightA) + len(highlightB)
            sublime.message_dialog(intraDiff + str(len(highlightA)) +
                                   ' lines removed, ' + str(len(highlightB)) +
                                   ' lines added\n' + str(numDiffs) +
                                   ' line differences total')
Exemple #60
0
def handle_message_request(params: dict):
    message = params.get("message", "(missing message)")
    actions = params.get("actions", [])
    addendum = "TODO: showMessageRequest with actions:"
    titles = list(action.get("title") for action in actions)
    sublime.message_dialog("\n".join([message, addendum] + titles))