コード例 #1
0
	def run(self, edit):
		view = self.view
		if not view.file_name().endswith('.js'):
			return

		jsContent = jsmin(view.substr(Region(0, view.size()))).replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n')
		if not jsContent:
			return

		template = os.path.splitext(view.file_name())[0] + '.mist'
		templateView = view.window().find_open_file(template)

		if templateView:
			region = templateView.find('"script"\s*:\s*"\K.*?(?=",)', 0, 0)

			if region == Region(-1, -1):
				scriptLine = '"script": "' + jsContent + '",\n  '
				templateView.insert(edit, 4, scriptLine)
				print('当前脚本已插入 ' + template)
			else:
				if jsContent == templateView.substr(region):
					return

				templateView.replace(edit, region, jsContent)
				print('当前脚本已同步至 ' + template)

			sublime.set_timeout_async(lambda:templateView.run_command('save'), 50)
			
		else:
			if os.path.isfile(template):
				replaceJSInTemplate(template, jsContent)
コード例 #2
0
ファイル: skins.py プロジェクト: deathaxe/sublime-skins
        def on_highlight(index):
            """Temporarily apply new skin, if quick panel selection changed.

            Arguments:
                index (int): Index of the highlighted skin.
            """
            if index == -1:
                return

            self.last_selected = index

            def preview_skin():
                # The selected row has changed since the timeout was created.
                if index != self.last_selected:
                    return
                for key, val in skins[index][PREF].items():
                    # backup settings before changing the first time
                    if key not in initial_prefs:
                        initial_prefs[key] = self.prefs.get(key)
                    if val:
                        self.prefs.set(key, val)
                    else:
                        self.prefs.erase(key)
            # start timer to delay the preview a little bit
            sublime.set_timeout_async(preview_skin, 250)
コード例 #3
0
ファイル: tags.py プロジェクト: asfaltboy/GitSavvy
    def get_remote_tags_list(self, remote, remote_name):
        if "tags" in remote:
            if remote["tags"]:
                msg = "\n".join(
                    "    {} {}".format(tag.sha[:7], tag.tag)
                    for tag in remote["tags"] if tag.tag[-3:] != "^{}"
                    )
            else:
                msg = NO_REMOTE_TAGS_MESSAGE

        elif "loading" in remote:
            msg = LOADING_TAGS_MESSAGE

        else:
            def do_tags_fetch(remote=remote, remote_name=remote_name):
                remote["tags"] = self.get_tags(remote_name, reverse=True)
                self.render()

            sublime.set_timeout_async(do_tags_fetch, 0)
            remote["loading"] = True
            msg = LOADING_TAGS_MESSAGE

        return self.template_remote.format(
            remote_name=remote_name,
            remote_tags_list=msg
            )
コード例 #4
0
	def on_load_async( self, view ):

		self.new_ColorScheme = None

		window = view.window()

		try:
			windowVariables = window.extract_variables()
			file     = windowVariables[ "file"      ]
			filePath = windowVariables[ "file_path" ]
			fileName = windowVariables[ "file_name" ]
		except( AttributeError, KeyError ) as e :
			return

		settings = sublime.load_settings( "ConditionalColorSchemes.sublime-settings" )
		preferred_ColorScheme_Set    = settings.get( "preferred_ColorScheme_Set", "" )
		include_FileName_In_FilePath = settings.get( "include_FileName_In_FilePath", "" )
		fileName_ColorSchemes        = settings.get( "fileName_ColorSchemes", [] )
		filePath_ColorSchemes        = settings.get( "filePath_ColorSchemes", [] )

		if include_FileName_In_FilePath == True:
			filePath = file

		if preferred_ColorScheme_Set == "filePath_ColorSchemes":
			self.get_Conditional_ColorScheme( fileName, fileName_ColorSchemes )
			self.get_Conditional_ColorScheme( filePath, filePath_ColorSchemes )
		elif preferred_ColorScheme_Set == "fileName_ColorSchemes":
			self.get_Conditional_ColorScheme( filePath, filePath_ColorSchemes )
			self.get_Conditional_ColorScheme( fileName, fileName_ColorSchemes )

		if self.new_ColorScheme != None:
			set_ColorScheme = lambda: view.settings().set( "color_scheme", self.new_ColorScheme )
			sublime.set_timeout_async( set_ColorScheme )
コード例 #5
0
ファイル: status.py プロジェクト: gwenzek/GitSavvy
    def run(self, edit):
        interface = ui.get_interface(self.view.id())

        non_cached_sections = (interface.get_view_regions("unstaged_files") +
                               interface.get_view_regions("untracked_files") +
                               interface.get_view_regions("merge_conflicts"))
        non_cached_lines = util.view.get_lines_from_regions(
            self.view,
            self.view.sel(),
            valid_ranges=non_cached_sections
        )
        non_cached_files = (
            os.path.join(self.repo_path, line.strip())
            for line in non_cached_lines
            if line[:4] == "    "
        )

        cached_sections = interface.get_view_regions("staged_files")
        cached_lines = util.view.get_lines_from_regions(
            self.view,
            self.view.sel(),
            valid_ranges=cached_sections
        )
        cached_files = (
            os.path.join(self.repo_path, line.strip())
            for line in cached_lines
            if line[:4] == "    "
        )

        sublime.set_timeout_async(
            lambda: self.load_diff_windows(non_cached_files, cached_files), 0)
コード例 #6
0
    def run(self, edit, key):
        self.key = key

        '''
        mom_is_wash_the_rama
        МамаМылаРаму
        MamaMilaRamu
        фывыфв
        '''

        sel = self.view.sel()[0]

        phrase = self.view.substr(sel)
        if '' == phrase.strip():
            phrase = self.view.substr(self.view.line(sel)).strip()
            if '' == phrase:
                return

        if re.search('[a-z]', phrase, re.I) is not None:
            direction = 'en-ru'
        else:
            direction = 'ru-en'

        phrase = re.sub('[_\-]', ' ', phrase)
        phrase = re.sub('([A-ZА-Я])', r' \1', phrase)

        def translate():
            self.request_translation(phrase, direction)

        sublime.set_timeout_async(translate, 0)
コード例 #7
0
ファイル: quick_stage.py プロジェクト: kostyll/GitSavvy
        def on_selection(id):
            if id == -1:
                return

            selection = menu_options[id]

            if not selection.requires_action:
                return

            elif selection.menu_text == ADD_ALL_UNSTAGED_FILES:
                self.git("add", "--update", ".")
                scope_of_action = "all unstaged files"

            elif selection.menu_text == ADD_ALL_FILES:
                self.git("add", "--all")
                scope_of_action = "all files"

            elif selection.is_untracked:
                self.git("add", "--", selection.filename)
                scope_of_action = "`{}`".format(selection.filename)

            else:
                self.git("add", "--update", "--", selection.filename)
                scope_of_action = "`{}`".format(selection.filename)

            sublime.status_message("Successfully added `{}`.".format(
                scope_of_action))

            sublime.set_timeout_async(self.run_async, 0)
コード例 #8
0
ファイル: ui.py プロジェクト: inaveu/GitSavvy
    def __init__(self, repo_path=None, view=None):
        if self._initialized:
            return
        self._initialized = True

        self.regions = {}

        subclass_attrs = (getattr(self, attr) for attr in vars(self.__class__).keys())

        self.partials = {
            attr.key: attr
            for attr in subclass_attrs
            if callable(attr) and hasattr(attr, "key")
            }

        for attr in vars(self.__class__).keys():
            if attr.startswith("template"):
                setattr(self, attr, dedent(getattr(self, attr)))

        if view:
            self.view = view
            self.render(nuke_cursors=False)
        else:
            self.create_view(repo_path)
            sublime.set_timeout_async(self.on_new_dashboard, 0)

        if hasattr(self, "tab_size"):
            self.view.settings().set("tab_size", self.tab_size)

        interfaces[self.view.id()] = self
コード例 #9
0
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)
コード例 #10
0
ファイル: gtags_plugin.py プロジェクト: roycyt/sublime-gtags
	def run(self, edit):

		logger.info("run GtagsJumpToDefinitionCommand!")
		# get current word
		self.symbol_name = self.view.substr(self.view.word(self.view.sel()[0].a))
		if len(self.symbol_name) != 0:
			sublime.set_timeout_async(self.jump_to_definition, 1)
コード例 #11
0
    def _with_open_file(self, filename, f):
        """Opens filename (relative to the plugin) in a new view, calls
        f(view) to perform the tests.
        """
        window = sublime.active_window()
        path = os.path.join(plugin_path, filename)
        view = window.open_file(path)
        q = queue.Queue()

        def async_test_view():
            try:
                # Wait for view to finish loading.
                for n in range(500):
                    if view.is_loading():
                        time.sleep(0.01)
                    else:
                        break
                else:
                    raise AssertionError('View never loaded.')
                # Run the tests on this view.
                f(view)
            except Exception as e:
                q.put(e)
            else:
                q.put(None)

        try:
            sublime.set_timeout_async(async_test_view, 0)
            msg = q.get()
            if msg:
                raise msg
        finally:
            window.focus_view(view)
            window.run_command('close_file')
コード例 #12
0
ファイル: Builder.py プロジェクト: AramRafeq/CppBuilder
    def run(self, edit):
        self.output = ''

        # async run the build so sublime doesn't hang

        sublime.set_timeout_async(self.buildruncheck)
        sublime.set_timeout_async(self.printoutput)
コード例 #13
0
 def start_stdout_watcher(self):
     sdk = SDK()
     t = StdoutWatcher(self, sdk.path)
     # Thread dies with the main thread.
     t.daemon = True
     # XXX: This is necessary. If we call t.start() directly, ST hangs.
     sublime.set_timeout_async(t.start, 0)
コード例 #14
0
ファイル: init.py プロジェクト: stoivo/GitSavvy
    def on_enter_directory(self, path):
        self.suggested_git_root = path
        if self.suggested_git_root and os.path.exists(os.path.join(self.suggested_git_root, ".git")):
            sublime.ok_cancel_dialog(RECLONE_CANT_BE_DONE)
            return

        sublime.set_timeout_async(self.do_clone, 0)
コード例 #15
0
ファイル: log.py プロジェクト: harshanarayana/GitSavvy
 def run(self, filename=None, limit=6000, author=None, log_current_file=False):
     self._pagination = 0
     self._filename = filename
     self._limit = limit
     self._author = author
     self._log_current_file = log_current_file
     sublime.set_timeout_async(self.run_async)
コード例 #16
0
ファイル: diff.py プロジェクト: abusalimov/GitSavvy
    def run(self, edit, reset=False):
        ignore_whitespace = self.view.settings().get("git_savvy.diff_view.ignore_whitespace")
        show_word_diff = self.view.settings().get("git_savvy.diff_view.show_word_diff")
        if ignore_whitespace or show_word_diff:
            sublime.error_message("You have to be in a clean diff to stage.")
            return None

        # Filter out any cursors that are larger than a single point.
        cursor_pts = tuple(cursor.a for cursor in self.view.sel() if cursor.a == cursor.b)

        self.diff_starts = tuple(region.a for region in self.view.find_all("^diff"))
        self.diff_header_ends = tuple(region.b for region in self.view.find_all("^\+\+\+.+\n(?=@@)"))
        self.hunk_starts = tuple(region.a for region in self.view.find_all("^@@"))
        hunk_starts_following_headers = {region.b for region in self.view.find_all("^\+\+\+.+\n(?=@@)")}
        self.hunk_ends = sorted(list(
            # Hunks end when the next diff starts.
            set(self.diff_starts[1:]) |
            # Hunks end when the next hunk starts, except for hunks
            # immediately following diff headers.
            (set(self.hunk_starts) - hunk_starts_following_headers) |
            # The last hunk ends at the end of the file.
            set((self.view.size(), ))
            ))

        sublime.set_timeout_async(lambda: self.apply_diffs_for_pts(cursor_pts, reset), 0)
コード例 #17
0
ファイル: diff.py プロジェクト: abusalimov/GitSavvy
    def apply_diffs_for_pts(self, cursor_pts, reset):
        in_cached_mode = self.view.settings().get("git_savvy.diff_view.in_cached_mode")

        # Apply the diffs in reverse order - otherwise, line number will be off.
        for pt in reversed(cursor_pts):
            hunk_diff = self.get_hunk_diff(pt)

            # The three argument combinations below result from the following
            # three scenarios:
            #
            # 1) The user is in non-cached mode and wants to stage a hunk, so
            #    do NOT apply the patch in reverse, but do apply it only against
            #    the cached/indexed file (not the working tree).
            # 2) The user is in non-cached mode and wants to undo a line/hunk, so
            #    DO apply the patch in reverse, and do apply it both against the
            #    index and the working tree.
            # 3) The user is in cached mode and wants to undo a line hunk, so DO
            #    apply the patch in reverse, but only apply it against the cached/
            #    indexed file.
            #
            # NOTE: When in cached mode, no action will be taken when the user
            #       presses SUPER-BACKSPACE.

            self.git(
                "apply",
                "-R" if (reset or in_cached_mode) else None,
                "--cached" if (in_cached_mode or not reset) else None,
                "-",
                stdin=hunk_diff
            )

        sublime.set_timeout_async(lambda: self.view.run_command("gs_diff_refresh"))
コード例 #18
0
ファイル: commit.py プロジェクト: zBMNForks/GitSavvy
    def run_async(self, commit_message=None):
        if commit_message is None:
            view_text = self.view.substr(sublime.Region(0, self.view.size()))
            help_text = self.view.settings().get("git_savvy.commit_view.help_text")
            commit_message = view_text.split(help_text)[0]

        include_unstaged = self.view.settings().get("git_savvy.commit_view.include_unstaged")

        show_panel_overrides = \
            sublime.load_settings("GitSavvy.sublime-settings").get("show_panel_for")

        self.git(
            "commit",
            "-q" if "commit" not in show_panel_overrides else None,
            "-a" if include_unstaged else None,
            "--amend" if self.view.settings().get("git_savvy.commit_view.amend") else None,
            "-F",
            "-",
            stdin=commit_message
            )

        # ensure view is not already closed (i.e.: when "commit_on_close" enabled)
        is_commit_view = self.view.settings().get("git_savvy.commit_view")
        if is_commit_view and self.view.window():
            self.view.window().focus_view(self.view)
            self.view.set_scratch(True)  # ignore dirty on actual commit
            self.view.window().run_command("close_file")
        else:
            sublime.set_timeout_async(
                lambda: util.view.refresh_gitsavvy(sublime.active_window().active_view()))
コード例 #19
0
ファイル: LuaFormat.py プロジェクト: FloydaGithub/LuaFormat
    def run(self, edit):
        # check whether the lua files
        suffix_setting = self.view.settings().get('syntax')
        file_suffix = suffix_setting.split('.')[0]
        if file_suffix[-3:].lower() != 'lua': return

        # get lines of replacement
        r = sublime.Region(0, self.view.size())
        self.view.unfold(r)
        
        # get characters of view
        lines = []
        for region in self.view.lines(r):
            cache = self.view.substr(region)
            if len(cache) == 0: cache = ' '
            lines.append(cache)

        # get cursor position before the replacement
        selection = self.view.sel()[0].b
        row, col = self.view.rowcol(selection)

        # replace the content after format
        print("Run Lua Format")
        self.view.replace(edit, r, lua_format(lines, get_settings()))

        # set tab_size from lua-format-setting
        self.view.run_command("set_setting", {"setting": "tab_size", "value": get_settings().get('tab_size', 4)})

        # deal cursor position
        selection = self.view.full_line(self.view.text_point(row - 1, 0)).b
        cursor_pos = sublime.Region(selection, selection)
        regions = self.view.sel()
        regions.clear()
        regions.add(cursor_pos)
        sublime.set_timeout_async(lambda: self.view.show(cursor_pos), 0)
コード例 #20
0
ファイル: quick_stage.py プロジェクト: asfaltboy/GitSavvy
        def on_selection(id):
            if id == -1:
                return

            selection = menu_options[id]

            if not selection.requires_action:
                return

            elif selection.menu_text == COMMIT:
                self.window.run_command("gs_quick_commit")
                return

            elif selection.menu_text == ADD_ALL_UNSTAGED_FILES:
                self.git("add", "--update", ".")
                scope_of_action = "all unstaged files"

            elif selection.menu_text == ADD_ALL_FILES:
                self.git("add", "--all")
                scope_of_action = "all files"

            elif selection.is_untracked:
                self.git("add", "--", selection.filename)
                scope_of_action = "`{}`".format(selection.filename)

            else:
                self.git("add", "--update", "--", selection.filename)
                scope_of_action = "`{}`".format(selection.filename)

            sublime.status_message("Successfully added `{}`.".format(
                scope_of_action))
            util.view.refresh_gitsavvy(self.window.active_view())

            sublime.set_timeout_async(self.run_async, 0)
コード例 #21
0
ファイル: common.py プロジェクト: wistful/SublimeAutoPEP8
def show_result(result):
    diffs = []
    not_fixed = ""
    has_changes = False

    # merge diffs.
    for command_result in result:
        if 'diff' in command_result:
            diffs.append(command_result['diff'])
        not_fixed += command_result['not_fixed']
        has_changes = has_changes or command_result.get('has_changes')

    # show status message.
    message = 'AutoPep8: No issues to fix.'
    if has_changes:
        message = 'AutoPep8: Issues were fixed.'
    sublime.status_message(message)

    show_error_panel(not_fixed)

    # show diff.
    if diffs:
        new_view('utf-8', '\n'.join(diffs))

    sublime.set_timeout_async(
        lambda: sublime.status_message(''), STATUS_MESSAGE_TIMEOUT)
コード例 #22
0
ファイル: progress.py プロジェクト: tedcheng/SublimeApex
    def run(self, i):
        if not self.thread.is_alive():
            if hasattr(self.thread, 'result') and not self.thread.result:
                sublime.status_message('')
                return

            # After thread is end, display feedback to end user
            # according to response
            result = self.api.result
            if isinstance(result, dict) and "success" in result and not result["success"]:
                if self.open_console: 
                    util.show_output_panel(message.SEPRATE.format(util.format_error_message(result)))

                settings = context.get_settings()
                delay_seconds = settings["delay_seconds_for_hidden_output_panel_when_failed"]
                sublime.set_timeout_async(util.hide_output_panel, delay_seconds * 1000)
            else:
                sublime.status_message(self.success_message)
            return

        before = i % self.size
        after = (self.size - 1) - before

        sublime.status_message('%s [%s=%s]' % \
            (self.message, ' ' * before, ' ' * after))

        if not after:
            self.addend = -1
        if not before:
            self.addend = 1
        i += self.addend

        sublime.set_timeout(lambda: self.run(i), 100)
コード例 #23
0
	def start_command(self, file_name, use_bundler=False):
		is_legal, file_path, arguments = PathHelper.get_file(file_name, self.window)

		if is_legal:
			sublime.set_timeout_async(lambda file_path=file_path,bundle=use_bundler, args=arguments: self.start_command_async(file_path, bundle, *args), 0)
		else:
			sublime.message_dialog("File: " + file_path+" does not exists")
コード例 #24
0
ファイル: __init__.py プロジェクト: DamnWidget/anaconda_go
    def init(self) -> None:
        """Initialize this project anagonda
        """

        if self.AVAILABLE is True:
            self.install_tools()

            def monitor():
                start = time.time()
                while not self.__tools_instaled() and time.time() - start <= 300:  # noqa
                    time.sleep(0.5)

                if time.time() - start >= 300:
                    sublime.message_dialog(
                        'Go utils not available for this project, look at the '
                        'log panel to fix any issue with your system, then '
                        'restart Sublime Text 3'
                    )
                else:
                    self._projects[self._project_name]['anagonda'] = True
                if os.name != 'nt':
                    sublime.set_timeout_async(
                        lambda: sublime.active_window().run_command(
                            'anaconda_go_fill_browse'), 0
                    )

            sublime.set_timeout_async(lambda: monitor(), 0)
コード例 #25
0
	def run(self):

		scriptPath = inspect.getframeinfo(inspect.currentframe()).filename
		scriptDir = os.path.dirname(scriptPath)

		os.chdir(scriptDir)

		files = ",".join(sorted(BrowsersyncState.watchPaths))
		index = sorted(BrowsersyncState.startFiles)[BrowsersyncState.startFileIndex]
		server = os.path.dirname(index)

		index = index.replace(server + "\\", "")

		plat = sublime.platform()

		killMethod = {
			'osx': 'killall -KILL node-osx',
			'linux': 'pkill -x node-linux',
			'windows': 'taskkill /im node-windows.exe /f /t'
		}.get(plat)

		os.system(killMethod)

		cmd = 'node-{0} browser_sync_launch.js "{1}" "{2}" "{3}"'
		cmd = cmd.format(plat, server,files, index)

		sublime.set_timeout_async(self.make_callback(cmd), 0)
コード例 #26
0
ファイル: goOracle.py プロジェクト: kdar/GoOracle
    def oracle(self, end_offset, begin_offset=None, mode="describe", callback=None):
        """ Builds the oracle shell command and calls it, returning it's output as a string.
        """

        pos = "#" + str(end_offset)
        if begin_offset is not None:
            pos = "#%i,#%i" %(begin_offset, end_offset)
        env = get_setting("env")

        # Build oracle cmd.
        cmd = "export GOPATH=\"%(go_path)s\"; export PATH=%(path)s; oracle -pos=%(file_path)s:%(pos)s -format=%(output_format)s %(mode)s %(scope)s"  % {
        "go_path": env["GOPATH"],
        "path": env["PATH"],
        "file_path": self.view.file_name(),
        "pos": pos,
        "output_format": get_setting("oracle_format"),
        "mode": mode,
        # TODO if scpoe is not set, use main.go under pwd or sublime project path.
        "scope": ' '.join(get_setting("oracle_scope"))} 

        if "GOROOT" in env:
            gRoot = "export GOROOT=\"%s\"; " % env["GOROOT"] 
            cmd = gRoot + cmd

        sublime.set_timeout_async(lambda: self.runInThread(cmd, callback), 0)
コード例 #27
0
    def run(self, edit):
        """Command to index open tab RF file and create db index table.

        Purpose of the command is create index, from the open tab.
        Index should contain all the resource and library imports and
        all global variables from variable tables and imported variable
        files.
        """
        log_file = get_setting(SettingObject.log_file)
        python_binary = get_setting(SettingObject.python_binary)
        table_dir = get_setting(SettingObject.table_dir)
        makedirs(path.dirname(log_file), exist_ok=True)
        open_tab = self.view.file_name()
        if not open_tab:
            message = 'Not able to index because no tabs are active'
            sublime.status_message(message)
            return
        db_table_name = self.get_table_name(open_tab)
        if db_table_name:
            file_ = open(log_file, 'a')
            sublime.set_timeout_async(self.run_single_index(
                    python_binary,
                    table_dir,
                    db_table_name,
                    file_
                ), 0)
            file_.close()
            message = update_current_view_index(self.view)
            sublime.status_message(message)
        else:
            message = 'Not able to index file: {0}'.format(open_tab)
            sublime.status_message(message)
コード例 #28
0
	def run(self, edit, action=None, clr_tests=False, text=None, sync_out=True, crash_line=None, value=None):
		v = self.view
		scope_name = v.scope_name(v.sel()[0].begin()).rstrip()
		file_syntax = scope_name.split()[0]
		if action == 'insert':
			v.insert(edit, v.sel()[0].begin(), text)
		elif action == 'make_opd':
			self.close_opds()
			self.create_opd(clr_tests=clr_tests, sync_out=sync_out)
		elif action == 'show_crash_line':
			pt = v.text_point(crash_line - 1, 0)
			v.erase_regions('crash_line')
			v.add_regions('crash_line', [sublime.Region(pt + 0, pt + 0)], \
				'variable.language.python', 'bookmark', \
				sublime.DRAW_SOLID_UNDERLINE)
			sublime.set_timeout_async(lambda pt=pt: v.show_at_center(pt), 39)
			# print(pt)
		elif action == 'get_var_value':
			self.get_var_value()

		elif action == 'show_var_value':
			self.show_var_value(value)

		elif action == 'toggle_using_debugger':
			self.toggle_using_debugger()

		elif action == 'sync_opdebugs':
			w = v.window()
			layout = w.get_layout()

			def slow_hide(w=w, layout=layout):
				if layout['cols'][1] < 1:
					layout['cols'][1] += 0.001
					w.set_layout(layout)
					sublime.set_timeout(slow_hide, 1)
				else:
					layout['cols'][1] = 1
					w.set_layout(layout)
					print('stopped')

			if len(layout['cols']) == 3:
				if layout['cols'][1] != 1:
					# hide opd panel
					self.ruler_opd_panel = min(layout['cols'][1], 0.93)
					layout['cols'][1] = 1
					# <This Region May be uncomment>
					#for x in w.views_in_group(1):
					#	x.run_command('test_manager', {'action': 'hide_text'})
					# < / >
					# slow_hide()
					w.set_layout(layout)
				else:
					# show opd panel
					layout['cols'][1] = self.ruler_opd_panel
					need_x = self.ruler_opd_panel
					# < This Region May be uncomment >
					#for x in w.views_in_group(1):
					#	x.run_command('test_manager', {'action': 'show_text'})
					# < / >
					w.set_layout(layout)
コード例 #29
0
def async_do(f, progress_msg="Evernote operation", done_msg=None):
    if not done_msg:
        done_msg = progress_msg + ': ' + "done!"
    status = {'done': False, 'i': 0}

    def do_stuff(s):
        try:
            f()
        except:
            pass
        finally:
            s['done'] = True

    def progress(s):
        if s['done']:
            sublime.status_message(done_msg)
        else:
            i = s['i']
            bar = "... [%s=%s]" % (' '*i, ' '*(7-i))
            sublime.status_message(progress_msg + bar)
            s['i'] = (i + 1) % 8
            sublime.set_timeout(lambda: progress(s), 100)

    sublime.set_timeout(lambda: progress(status), 0)
    sublime.set_timeout_async(lambda: do_stuff(status), 0)
コード例 #30
0
ファイル: blame.py プロジェクト: dufferzafar/GitSavvy
    def scroll_to(self, coords):
        pattern = r".{{40}} \| {lineno: >4} ".format(lineno=coords[0] + 1)
        corresponding_region = self.view.find(pattern, 0)
        blame_view_pt = corresponding_region.b

        self.view.sel().add(sublime.Region(blame_view_pt, blame_view_pt))
        sublime.set_timeout_async(lambda: self.view.show_at_center(blame_view_pt), 0)
コード例 #31
0
ファイル: checkout.py プロジェクト: rommelb8/GitSavvy
 def run(self, branch=None):
     sublime.set_timeout_async(lambda: self.run_async(branch), 0)
コード例 #32
0
ファイル: branch.py プロジェクト: zBMNForks/GitSavvy
 def run(self, edit):
     sublime.set_timeout_async(self.run_async)
コード例 #33
0
ファイル: branch.py プロジェクト: zBMNForks/GitSavvy
 def run(self, edit, force=False):
     self.force = force
     sublime.set_timeout_async(self.run_async, 0)
コード例 #34
0
def _plugin_loaded():
    sublime.set_timeout_async(load)
コード例 #35
0
ファイル: ui.py プロジェクト: taubi19/GitSavvy
 def run(self, edit, nuke_cursors=False):
     sublime.set_timeout_async(self.run_async, 0)
     self.nuke_cursors = nuke_cursors
コード例 #36
0
 def run(self):
     sublime.set_timeout_async(self.run_async, 0)
コード例 #37
0
ファイル: checkout.py プロジェクト: rommelb8/GitSavvy
 def run(self, remote_branch=None):
     sublime.set_timeout_async(lambda: self.run_async(remote_branch))
コード例 #38
0
ファイル: ansi.py プロジェクト: nestedfunction/SublimeANSI
 def detect_left_ansi(self, view):
     sublime.set_timeout_async(partial(self.check_left_ansi, view), 50)
コード例 #39
0
    def callback(self, folder):
        def remove_folder():
            sampy_manager.remove_folder(folder)

        sublime.set_timeout_async(remove_folder, 0)
コード例 #40
0
ファイル: util.py プロジェクト: warlock90000/DotFiles
def generate_menus(**kwargs):
    """Asynchronously call generate_menus_async."""
    sublime.set_timeout_async(generate_menus_async, 0)
コード例 #41
0
ファイル: log.py プロジェクト: Siyouardi/GitSavvy
 def run(self, *args, commit_hash=None, file_path=None, **kwargs):
     if commit_hash:
         self.do_action(commit_hash, file_path=file_path, **kwargs)
     else:
         sublime.set_timeout_async(
             lambda: self.run_async(file_path=file_path, **kwargs))
コード例 #42
0
 def update_build_status(self, view):
     sublime.set_timeout_async(lambda: self.update_build_status_async(view))
コード例 #43
0
	def run(self, edit, host=None, path=None, defaultHost=DEFAULT_HOST, defaultPath=DEFAULT_PATH):
		window = self.view.window()

		# If no host or path was passed in, show a prompt for the user to choose
		if host is None or path is None:
			def on_done_host(host):
				def on_done_path(path):
					# Once the user has chosen a host and path, re-run the command with the new values
					window.active_view().run_command("remote_download", {"host": host, "path": path})

				window.show_input_panel(
				"Enter a file path to download:",
				defaultPath.format(**TEMPLATE_ARGS),
				on_done=on_done_path,
				on_change=None,
				on_cancel=None)

			window.show_input_panel(
				"Enter a host name to download from:",
				defaultHost.format(**TEMPLATE_ARGS),
				on_done=on_done_host,
				on_change=None,
				on_cancel=None)
			return

		host = host.format(**TEMPLATE_ARGS)
		path = path.format(**TEMPLATE_ARGS)

		# Will store the downloaded file as bytes
		file = None
		# Try to download file `TRIES' times before giving up
		for i in range(TRIES):
			# If scp returns a non-0 code, an error is raised and caught
			try:
				# -B ensures scp will fail if a password is asked for
				file = subprocess.check_output(["scp", "-B", "{}:{}".format(host, path), "/dev/stdout"])
				break
			except subprocess.CalledProcessError as err:
				if err.returncode == 0:
					raise(err)
		else:
			# The file couldn't be downloaded and an error message is shown to the user
			sublime.error_message("The file at {}:{} couldn't be downloaded.".format(host, path))
			return
		
		# A temporary file is made on disk to store the downloaded file
		filename = RemoteDownloadCommand.makeTmpFile(path, file)

		# Open a new tab for the file (or open a pre-existing one)
		view = window.open_file(filename)

		# openFile is run once the view is done loading
		def openFile():
			if view.is_loading():
				# If it's not done loading, try again in 200 ms
				sublime.set_timeout_async(openFile, 200)
			else:
				# Set up settings for the file for easier uploading later
				view.settings().set("remote_edit_tmp_file", filename)
				view.settings().set("remote_edit_origin", "{}:{}".format(host, path))
				view.settings().set("remote_edit_is_remote", True)
				view.set_status("remote_edit_status", "Uplaoding to {}:{}".format(host, path))
		sublime.set_timeout_async(openFile, 0)
コード例 #44
0
 def run(self, edit):
     sublime.set_timeout_async(self.run_release, 0)
コード例 #45
0
    def on_post_text_command(self, view, command_name, args):
        # print("on_post_text_command, command:", command_name, "args: ", args)
        if command_name == "replace_completion_with_next_completion":
            self._replace_completion_with_next_completion = False

        if command_name in [
                "left_delete", "commit_completion", "insert_best_completion",
                "replace_completion_with_next_completion"
        ]:
            self._stop_completion = True
            view.hide_popup()

        if command_name in [
                "commit_completion", "insert_best_completion",
                "replace_completion_with_next_completion"
        ]:

            current_location = view.sel()[0].end()
            previous_location = self._last_query_location
            end_of_line = view.line(
                sublime.Region(current_location, current_location))
            substitution = view.substr(
                sublime.Region(previous_location, current_location))

            existing_choice = next(
                (x for x in self._results
                 if x["new_prefix"] == self._completion_prefix + substitution),
                None)

            if existing_choice is not None:

                if existing_choice["old_suffix"].strip():

                    # print("existing_choice:", json.dumps(existing_choice))
                    # print("old_suffix: ", existing_choice["old_suffix"])
                    # print("new_suffix: ", existing_choice["new_suffix"])

                    end_search_location = min(
                        current_location + len(substitution) +
                        len(existing_choice["new_suffix"]), end_of_line.end())

                    start_search_location = current_location + len(
                        existing_choice["new_suffix"])

                    after_substitution = view.substr(
                        sublime.Region(start_search_location,
                                       end_search_location))

                    # print("substitution: ", substitution)
                    # print("after_substitution: ", after_substitution)

                    old_suffix_index = after_substitution.find(
                        existing_choice["old_suffix"])
                    if old_suffix_index != -1:

                        start_erase_location = start_search_location + old_suffix_index
                        args = {
                            "begin":
                            start_erase_location,
                            "end":
                            start_erase_location +
                            len(existing_choice["old_suffix"]),
                            "old_suffix":
                            existing_choice["old_suffix"]
                        }
                        view.run_command("tab_nine_post_substitution", args)

        if command_name in ["insert_snippet"]:
            # print("running insert snippet")
            def _run_compete():
                view.run_command(
                    'auto_complete', {
                        'api_completions_only': False,
                        'disable_auto_insert': True,
                        'next_completion_if_showing': True,
                        'auto_complete_commit_on_tab': True,
                    })

            view.run_command('hide_auto_complete')
            sublime.set_timeout_async(_run_compete, 0)
            return
コード例 #46
0
ファイル: blame.py プロジェクト: tomv564/GitSavvy
 def run(self, *args, commit_hash=None):
     sublime.set_timeout_async(lambda: self.run_async(self.file_path), 0)
コード例 #47
0
ファイル: inline_diff.py プロジェクト: kostyll/GitSavvy
 def run(self, edit, **kwargs):
     sublime.set_timeout_async(lambda: self.run_async(**kwargs), 0)
コード例 #48
0
	def run(self, edit, src=None, write=True, defaultHost=DEFAULT_HOST, defaultPath=DEFAULT_PATH):
		window = self.view.window()
		view = self.view
		settings = view.settings()

		# If no src was passed, try to get it from the file's settings or prompt the user if that fails
		if src is None:
			src = settings.get("remote_edit_origin")
			if src is None:
				# Prompt the user for a host and path name to upload to
				def on_done_host(host):
					def on_done_path(path):
						# Re-run the command with the new values
						view.run_command("remote_upload", {"src": "{}:{}".format(host, path)})

					window.show_input_panel(
					"Enter a path to upload file to:",
					defaultPath.format(**TEMPLATE_ARGS),
					on_done=on_done_path,
					on_change=None,
					on_cancel=None)

				window.show_input_panel(
					"Enter a host name to upload to:",
					defaultHost.format(**TEMPLATE_ARGS),
					on_done=on_done_host,
					on_change=None,
					on_cancel=None)
				return

		src = src.format(**TEMPLATE_ARGS)

		# Update the file's settings to be able to upload without having to re-choose in the future
		settings.set("remote_edit_origin", src)
		settings.set("remote_edit_is_remote", True)
		view.set_status("remote_edit_status", "Uploading to {}".format(src))

		# Get the location of the on-disk copy of the file
		diskLoc = view.file_name() or settings.get("remote_edit_tmp_file")

		# If it couldn't be found, make a new temporary file to store it
		if diskLoc is None:
			write = True
			diskLoc = RemoteDownloadCommand.makeTmpFile(src.split(":")[1], view.substr(sublime.Region(0, view.size())), write=False)
			settings.set("remote_edit_tmp_file", diskLoc)

		# Shows "Uploading..." in the status bar to show the user stuff is happening
		window.status_message("Uploading...")

		# doUpload is done asynchronously to prevent freezing
		def doUpload():
			# If `write' is True, write to the temporary file before saving (may not be necessary if the user saved manually)
			if write:
				diskFile = open(diskLoc, "w+")
				diskFile.write(view.substr(sublime.Region(0, view.size())))
				diskFile.close()

			# Try `TRIES' number of times to upload
			for i in range(TRIES):
				try:
					subprocess.check_output(["scp", "-B", diskLoc, src])
					window.status_message("Uploaded successfully")
					break
				except subprocess.CalledProcessError as err:
					if err.returncode == 0:
						raise(err)
			else:
				# Show an error if the upload failed
				sublime.error_message("The file at {}:{} couldn't be uploaded.".format(src, path))

		sublime.set_timeout_async(doUpload, 0)
コード例 #49
0
ファイル: subex.py プロジェクト: inanme/subex
def main_thread(callback, *args, **kwargs):
    sublime.set_timeout_async(functools.partial(callback, *args, **kwargs), 0)
コード例 #50
0
    def on_query_completions(self, view, prefix, locations):

        # print("in on_query_completions")

        if not view.match_selector(locations[0], "source | text"):
            return ([], sublime.INHIBIT_WORD_COMPLETIONS
                    | sublime.INHIBIT_EXPLICIT_COMPLETIONS)

        last_region = view.substr(
            sublime.Region(max(locations[0] - 2, 0), locations[0])).rstrip()
        if last_region in ["", os.linesep]:
            # print("empty character query: ")
            return ([], sublime.INHIBIT_WORD_COMPLETIONS
                    | sublime.INHIBIT_EXPLICIT_COMPLETIONS)

        if self._replace_completion_with_next_completion == True:
            self._replace_completion_with_next_completion = False
            return self._completions

        if self._last_query_location == locations[
                0] and self._last_location is None:
            # print("last location is None")
            return self._completions

        self._last_query_location = locations[0]
        self._completion_prefix = prefix
        old_prefix = None
        if self._last_location != locations[0]:
            temp_location = self._last_location
            self._last_location = locations[0]

            def _run_complete():
                request = {
                    "Autocomplete": {
                        "before": self.before,
                        "after": self.after,
                        "filename": view.file_name(),
                        "region_includes_beginning":
                        self.region_includes_beginning,
                        "region_includes_end": self.region_includes_end,
                        "max_num_results": 5,
                    }
                }
                response = tabnine_proc.request(request)
                if response is None:
                    self._results = []
                    self._user_message = []
                    return

                # print("-----------")
                # print("response: ", json.dumps(response))
                # print("-----------")

                self._results = response["results"]
                self._user_message = response["user_message"]
                old_prefix = response["old_prefix"]

                if len(self._results) < 1:
                    return

                if self._results and self._user_message and view.window():
                    view.window().status_message(" ".join(self._user_message))
                elif view.window():
                    view.window().status_message("TabNine")

                view.run_command(
                    'auto_complete', {
                        'api_completions_only': False,
                        'disable_auto_insert': True,
                        'next_completion_if_showing': True,
                        'auto_complete_commit_on_tab': True,
                    })

            view.run_command('hide_auto_complete')
            sublime.set_timeout_async(_run_complete, 0)

            return ([], sublime.INHIBIT_WORD_COMPLETIONS
                    | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
        if self._last_location == locations[0]:
            self._last_location = None
            if len(self._results) == 1 and old_prefix is None:
                existing = view.substr(
                    sublime.Region(max(locations[0] - (len(prefix) + 2), 0),
                                   locations[0]))
                is_tabNine_command = existing == "::{}".format(prefix)
                if is_tabNine_command:
                    view.show_popup(
                        self._results[0]["new_prefix"],
                        sublime.COOPERATE_WITH_AUTO_COMPLETE,
                        location=locations[0],
                        max_width=1500,
                        max_height=1200,
                        on_navigate=webbrowser.open,
                    )
                else:
                    view.hide_popup()

            self._completions = [
                (r.get("new_prefix") + "\t" + r.get("detail", "TabNine"),
                 r.get("new_prefix") + "$0" + r.get("new_suffix", ""))
                for r in self._results
            ]

            # print("completions:", self._completions)

            flags = sublime.INHIBIT_WORD_COMPLETIONS
            if len(self._completions) > 0:
                flags = 0
            return (self._completions, flags)
コード例 #51
0
ファイル: push.py プロジェクト: kostyll/GitSavvy
 def run(self):
     sublime.set_timeout_async(lambda: self.do_push())
コード例 #52
0
 def show(self):
     if self.ask_remote_first:
         show_remote_panel(lambda remote: sublime.set_timeout_async(
             lambda: self.on_remote_selection(remote), 100))
     else:
         self.select_branch(remote=None)
コード例 #53
0
ファイル: commands.py プロジェクト: gragusa/Terminus
 def run(self, *args, **kwargs):
     sublime.set_timeout_async(lambda: self.run_async(*args, **kwargs))
コード例 #54
0
 def run(self, edit):
     self.interface = ui.get_interface(self.view.id())
     sublime.set_timeout_async(self.run_async, 0)
コード例 #55
0
ファイル: pm.py プロジェクト: ItsDom/Project-Manager
    def edit_project(self, project):
        def on_open():
            self.window.open_file(self.project_file_name(project))

        sublime.set_timeout_async(on_open, 100)
コード例 #56
0
ファイル: drp.py プロジェクト: dugo3number2/SublimeDiscordRP
def plugin_loaded():
    global settings
    settings = sublime.load_settings(SETTINGS_FILE)
    if settings.get('connect_on_startup'):
        sublime.set_timeout_async(partial(connect, silent=True), 0)
コード例 #57
0
 def next_flash():
     view.erase_regions(cls._UNRESOLVED_KEY)
     sublime.set_timeout_async(
         lambda: cls.flash_invalid(view, points, times - 1),
         cls._FLASH_INTERVAL)
コード例 #58
0
ファイル: checkout.py プロジェクト: jmcollis/GitSavvy
 def run(self, commit_hash, file_path):
     self._commit_hash = commit_hash
     self._file_path = file_path
     sublime.set_timeout_async(self.run_async)
コード例 #59
0
    def on_query_completions(self, view, prefix, locations):
        def _run_complete():

            response = autocomplete(
                self.before,
                self.after,
                view.file_name(),
                self.region_includes_beginning,
                self.region_includes_end,
            )
            if response is None:
                self._results = []
                self._user_message = []
                return

            logger.debug("--- response ---")
            logger.jsonstr(response)
            logger.debug("--- end response ---")

            self._results = response["results"]
            self._user_message = response["user_message"]
            self._old_prefix = response["old_prefix"]

            if len(self._results) < 1:
                return

            if self._results and self._user_message and view.window():
                view.window().status_message(" ".join(self._user_message))

            view.run_command(
                "auto_complete",
                {
                    "api_completions_only": True,
                    "disable_auto_insert": True,
                    "next_completion_if_showing": False,
                    "auto_complete_commit_on_tab": True,
                },
            )

        EMPTY_COMPLETION_LIST = (
            [],
            sublime.INHIBIT_WORD_COMPLETIONS
            | sublime.INHIBIT_EXPLICIT_COMPLETIONS,
        )

        if should_return_empty_list(view, locations, prefix):
            return EMPTY_COMPLETION_LIST

        if is_tabnine_disabled(view):
            return EMPTY_COMPLETION_LIST if prefix.strip() == "" else None

        if self._replace_completion_with_next_completion:
            self._replace_completion_with_next_completion = False
            return self.get_completions_with_flags()

        if self._last_query_location == locations[
                0] and self._last_location is None:
            if len(self._completions) == 0 and prefix == "":
                self._last_location = locations[0]
                active_view().run_command("hide_auto_complete")
                sublime.set_timeout_async(_run_complete, 0)
                return EMPTY_COMPLETION_LIST

            if self.has_competions():
                return (self._completions, sublime.INHIBIT_WORD_COMPLETIONS)
            else:
                return EMPTY_COMPLETION_LIST

        self._last_query_location = locations[0]
        self._completion_prefix = prefix
        self._old_prefix = None
        if self._last_location != locations[0]:
            self._last_location = locations[0]
            active_view().run_command("hide_auto_complete")
            sublime.set_timeout_async(_run_complete, 0)

            return EMPTY_COMPLETION_LIST
        if self._last_location == locations[0]:
            self._last_location = None
            self.handle_tabnine_commands(view, locations, prefix)

            self._completions = self.get_completion()

            logger.debug("completions: {}".format(self._completions))

            return self.get_completions_with_flags()
コード例 #60
0
ファイル: pm.py プロジェクト: ItsDom/Project-Manager
 def open_in_new_window(self, project):
     self.check_project(project)
     self.close_project(project)
     sublime.set_timeout_async(
         lambda: subl(["-n", self.project_file_name(project)]), 500)