我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sublime.status_message()。
def show_output_panel(self, text=''): if self.silent: self.status_message(text) return if self.results_in_new_tab: new_tab_path = os.path.join(self.commandbox_results_path(), "Commandbox Results") self.output_view = self.window.open_file(new_tab_path) self.output_view.set_scratch(True) else: self.output_view = self.window.get_output_panel("commandbox_output") self.show_panel() self.output_view.settings().set("scroll_past_end", False) self.add_syntax() self.appendToOutput(text)
def run(self, i): if self.stopped: 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)
def error_command(method): """ A decorator that executes method only if the current view has errors. This decorator is meant to be used only with the run method of sublime_plugin.TextCommand subclasses. A wrapped version of method is returned. """ 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.status_message('No lint errors.') return run
def openDiffInTab(viewHandle, edit, oldTextName, newTextName, oldText, newText): diffs = difflib.unified_diff(oldText.splitlines(), newText.splitlines(), oldTextName, newTextName) diffText = u"\n".join(line for line in diffs) if diffText == "": sublime.status_message("No changes between revisions.") else: scratch = viewHandle.window().new_file() scratch.set_scratch(True) scratch.set_name("{old} -> {new}".format(old = oldTextName, new = newTextName)) scratch.set_syntax_file("Packages/Diff/Diff.tmLanguage") if (int(sublime.version()) >= 3000): scratch.run_command("append", {"characters": diffText}) else: scratch.insert(edit, 0, diffText)
def compilePapyrus(args, window, optimize, release, final): config = getPrefs(os.path.dirname(args["cmd"])) if config: scriptPath = args["cmd"][len(config["scripts"])+1:] args["cmd"] = [config["compiler"], scriptPath] args["cmd"].append("-f={0}".format(config["flags"])) args["cmd"].append("-i={0}".format(config["import"])) args["cmd"].append("-o={0}".format(config["output"])) if optimize: args["cmd"].append("-op") if release: args["cmd"].append("-r") if final: args["cmd"].append("-final") args["working_dir"] = os.path.dirname(config["compiler"]) window.run_command("exec", args) else: sublime.status_message("No configuration for {0}".format(os.path.dirname(args["cmd"])))
def run(self, edit): try: if(player.index == len(player.titles_list) - 1): player.index = 0 else: player.index = player.index + 1 if(os.path.exists(player.path_list[player.index]) == False): if(player.index == len(player.titles_list) - 1): player.index = 0 reload_lists() player.set_media(player.media_list_mod[player.index]) sublime.status_message(player.titles_list[player.index]) player.play() except Exception: sublime.status_message("Add a Song path")
def run(self, i): if not self.thread.is_alive(): if hasattr(self.thread, 'result') and not self.thread.result: sublime.status_message('') return sublime.status_message(self.success_message) if self.callback != None: self.callback() 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)
def replace(self, query): if query.startswith("#"): query = query[1:] views = self.window.views() else: views = [self.window.active_view()] total = 0 for view in views: original_string = view.substr(sublime.Region(0, view.size())) pp = '\\b' + self.original_text + '\\b' p = re.compile(pp) (new_string, count) = p.subn(query, original_string) total = total + count if new_string != original_string: view.run_command('replace_content', {"new_content": new_string}) sublime.status_message("Replace {0} occurrences from {1} files".format(total, len(views))) pass
def search(self, query): if self.grep_command is not None: command = self.grep_command.format(pipes.quote(query)) elif self.show_in_view: command = grepFormatStr().format( grepPath(self.window), pipes.quote(query) ) else: # we need quick results command = quickGrepFormatStr().format( grepPath(self.window), pipes.quote(query) ) sublime.status_message("grepping {0} ...".format(pipes.quote(query))) output, _ = run_bash_for_output(command) lines = output.split('\n') self.show_results(query, lines)
def run(self, edit): file = self.view.file_name() d = settings().get('depth') fD = Mapper.DEPTH[1] if file in fD and fD[file] < 4: fD[file] += 1 elif d < 4: fD[file] = d + 1 win().status_message(' Current CodeMap Depth: %d' % fD[file]) refresh_map_for(self.view) synch_map(self.view) # ===============================================================================
def run(self, edit): file = self.view.file_name() d = settings().get('depth') fD = Mapper.DEPTH[1] if file in fD and fD[file] > 0: fD[file] -= 1 elif d > 0: fD[file] = d - 1 win().status_message(' Current CodeMap Depth: %d' % fD[file]) refresh_map_for(self.view) synch_map(self.view) # ===============================================================================
def run(self, paths = []): items = [] for item in SideBarSelection(paths).getSelectedImages(): try: image_type, width, height = self.getImageInfo(item.path()) items.append('<img src="'+item.pathAbsoluteFromProjectEncoded()+'" width="'+str(width)+'" height="'+str(height)+'">') except: items.append('<img src="'+item.pathAbsoluteFromProjectEncoded()+'">') if len(items) > 0: sublime.set_clipboard("\n".join(items)); if len(items) > 1 : sublime.status_message("Items copied") else : sublime.status_message("Item copied") # http://stackoverflow.com/questions/8032642/how-to-obtain-image-size-using-standard-python-class-without-using-external-lib
def run(self, paths = []): items = [] for item in SideBarSelection(paths).getSelectedItems(): if item.isUnderCurrentProject(): txt = item.url('url_production') try: txt = urlunquote(txt.encode('utf8')).decode('utf8') except TypeError: txt = urlunquote(txt) items.append(txt) if len(items) > 0: sublime.set_clipboard("\n".join(items)); if len(items) > 1 : sublime.status_message("Items URL copied") else : sublime.status_message("Item URL copied")
def get_rel_path_file(self): # to support unsaved file (like Tail) logn = self.view.file_name() if logn: text = self.view.substr(sublime.Region(0, self.view.size())) else: logn = self.view.settings().get('filepath', '') text = fread(logn) files_l = re.compile(LINK_REGX_RELPATH).findall(text) rel_path = False if len(files_l) > 0: for file_name in files_l: if not os.path.isabs(file_name): # use the first in relative path list rel_path = True break if rel_path: return file_name else: sublime.status_message("Log Highlight : There is no relative path file") return "" else: sublime.status_message("Log Highlight : There is no openable file path") return ""
def start_server(server_binary_args, working_dir, env): debug("starting " + str(server_binary_args)) si = None if os.name == "nt": si = subprocess.STARTUPINFO() # type: ignore si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW # type: ignore try: process = subprocess.Popen( server_binary_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=working_dir, env=env, startupinfo=si) return Client(process, working_dir) except Exception as err: sublime.status_message("Failed to start LSP server {}".format(str(server_binary_args))) exception_log("Failed to start server", err)
def response_handler(self, response): handler_id = int(response.get("id")) # dotty sends strings back :( if 'result' in response and 'error' not in response: result = response['result'] if settings.log_payloads: debug(' ' + str(result)) if handler_id in self._response_handlers: self._response_handlers[handler_id](result) else: debug("No handler found for id" + response.get("id")) elif 'error' in response and 'result' not in response: error = response['error'] if settings.log_payloads: debug(' ' + str(error)) if handler_id in self._error_handlers: self._error_handlers[handler_id](error) else: sublime.status_message(error.get('message')) else: debug('invalid response payload', response)
def alive_indicator(): i = 0 s = '----x----' c = [s[i:] + s[:i] for i in range(len(s))] # cycler = itertools.cycle(['|', '/', '-', '\\']) cycler = itertools.cycle(itertools.chain(c)) def ping(): nonlocal i i += 1 if i % 10 == 0: try: msg = "%s %s" % (State['options'], State['target']) except KeyError: msg = '' sublime.status_message( 'Running [%s] %s' % (next(cycler), msg)) return ping
def process(self, usages: bool=False, data: Dict =None) -> None: """Process the definitions """ view = self.text.view if not data['success']: sublime.status_message('Unable to find {}'.format( view.substr(view.word(view.sel()[0]))) ) return definitions = data['goto'] if not usages else data['usages'] if len(definitions) == 0: sublime.status_message('Unable to find {}'.format( view.substr(view.word(view.sel()[0]))) ) return if definitions is not None and len(definitions) == 1 and not usages: self._jump(*definitions[0]) else: self._show_options(definitions, usages)
def update(self, i): """Update the progress bar """ if self.die: return size = 8 pos = i % size status = '{}={}'.format(' ' * pos, ' ' * ((size - 1) - pos)) sublime.status_message('{} [{}]'.format( self.messages['start'], status) ) if not (size - 1) - pos: self.addition = -1 if not pos: self.addition = 1 i += self.addition sublime.set_timeout_async(lambda: self.update(i), 100)
def on_success(self, data): """Called when a result comes from the query """ if not data['result']: sublime.status_message('Could not find symbol') return symbols = [] for result in data['result']: symbols.append({ 'title': result[0], 'location': 'File: {} Line: {} Column: {}'.format( result[1], result[2], result[3] ), 'position': '{}:{}:{}'.format(result[1], result[2], result[3]) }) ExplorerPanel(self.view, symbols).show([])
def prepare_data(self, data: Dict[str, Any]) -> None: """Prepare the data to present in the quick panel """ if not data['success'] or data['errors'] is None: sublime.status_message('Unable to run McCabe checker...') return if len(data['errors']) == 0: view = self.window.active_view() threshold = get_settings(view, 'mccabe_threshold', 7) sublime.status_message( 'No code complexity beyond {} was found'.format(threshold) ) self._show_options(data['errors'])
def compile_once(self, window_for_panel, triggered_for_file): if self.is_compiling and self.compiler is not None: if self.compiler.is_alive(): sublime.status_message('Still compiling. Use Goto Anything > "ArcticTypescript: Terminate All Builds" to cancel.') self.compiler._show_output("") else: self.is_compiling = False if not self.is_compiling: self.is_compiling = True self.compiler = Compiler(self, window_for_panel, triggered_for_file) self.compiler.daemon = True sublime.status_message('Compiling') self.compiler.start()
def prepare_list(self, tss_result_json): del self.completion_list[:] try: entries = json.loads(tss_result_json) entries = entries['entries'] except: if tss_result_json.strip() == 'null': sublime.status_message('ArcticTypescript: no completions available') else: Debug('error', 'Completion request failed: %s' % tss_result_json) return 0 for entry in entries: if self.interface and entry['kind'] != 'primitive type' and entry['kind'] != 'interface' : continue key = self._get_list_key(entry) value = self._get_list_value(entry) self.completion_list.append((key,value)) self.completion_list.sort() return len(self.completion_list) # GET LISTE
def display_error_in_status_if_cursor(self, view): """ Displays the error message in the sublime status line if the cursor is above an error (in source code). For the click on the error list, see T3SVIEWS.ERROR.on_click() """ try: error = self._get_error_at(view.sel()[0].begin(), view.file_name()) except: # no selection in view return if error is not None: sublime.status_message(error) self.previously_error_under_cursor = True elif self.previously_error_under_cursor: # only clear once sublime.status_message('') self.previously_error_under_cursor = False
def run(self): issue_post = get_issue_post(self.view) log("preparing posting issue " + str(issue_post[ 'issue'])) post_result = self.issue_list.post_issue( data=json.dumps(issue_post['issue'])) if post_result.status_code in (200, 201): issue = post_result.json() if len(issue_post['label']) != 0: self.issue_list.attach_labels(issue['number'], issue_post['label']) repo_info = (self.issue_list.username, self.issue_list.repo_name, None) self.view.settings().set("new_issue", False) print_issue_in_view = PrintIssueInView( self.issue_list, issue['number'], self.issue_storage, repo_info, repo_info_storage, self.view) print_issue_in_view.start() else: sublime.status_message( "Issue not Posted, error code {} please try again.".format( str(post_result.status_code)))
def run(self, edit, *args): sublime.status_message('Processing PlantUML') self.view.set_status('plant', 'Processing PlantUML') content = self.view.substr(sublime.Region(0, self.view.size())) img_file_name = os.path.splitext(self.view.file_name())[0] + '.png' with open(img_file_name, 'w') as image_file: p = Popen( ['docker', 'run', '-i', '--rm', 'plantuml'], stdout=image_file, stdin=PIPE, stderr=PIPE ) p.communicate(input=bytes(content, 'utf-8'))[0] view = self.find_view(img_file_name) if view is None: view = self.view view.window().open_file(img_file_name) view.window().focus_view(self.view) view.erase_status('plant')
def show(self,region,location): # If nothing is selected expand selection to word if region.empty() : region = self.view.word(region) # Make sure a whole word is selected elif (self.view.classify(region.a) & sublime.CLASS_WORD_START)==0 or (self.view.classify(region.b) & sublime.CLASS_WORD_END)==0: if (self.view.classify(region.a) & sublime.CLASS_WORD_START)==0: region.a = self.view.find_by_class(region.a,False,sublime.CLASS_WORD_START) if (self.view.classify(region.b) & sublime.CLASS_WORD_END)==0: region.b = self.view.find_by_class(region.b,True,sublime.CLASS_WORD_END) v = self.view.substr(region) # trigger on valid word only if not re.match(r'^[A-Za-z_]\w*$',v): return # s,ti = self.get_type(v,region) if not s: sublime.status_message('No definition found for ' + v) else : s = self.color_str(s,ti) s = '<style>{css}</style><div class="content">{txt}</div>'.format(css=tooltip_css, txt=s) self.view.show_popup(s,location=location, flags=tooltip_flag, max_width=500, on_navigate=self.on_navigate)
def get_list_file(self, projname, callback=None): global list_module_files global lmf_update_ongoing lmf_update_ongoing = True lmf = [] for folder in sublime.active_window().folders(): for root, dirs, files in os.walk(folder): for fn in files: if fn.lower().endswith(('.vhd','.vho','.vhdl')): ffn = os.path.join(root,fn) f = open(ffn) if os.stat(ffn).st_size: s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) if s.find(b'entity') != -1: lmf.append(ffn) elif s.find(b'component') != -1: lmf.append(ffn) sublime.status_message('List of module files updated') list_module_files[projname] = lmf[:] lmf_update_ongoing = False if callback: callback()
def run(self, edit): def setIndentWithSpace(text): s = sublime.load_settings('phpfmt.sublime-settings') v = text.strip() if not v: v = False else: v = int(v) s.set("indent_with_space", v) sublime.save_settings('phpfmt.sublime-settings') sublime.status_message("phpfmt (indentation): done") sublime.active_window().active_view().run_command("fmt_now") s = sublime.load_settings('phpfmt.sublime-settings') spaces = s.get("indent_with_space", 4) if not spaces: spaces = "" spaces = str(spaces) self.view.window().show_input_panel('how many spaces? (leave it empty to return to tabs)', spaces, setIndentWithSpace, None, None)
def do_rename(view, byte_offset, new_name, simulate): new_name = new_name.strip() if new_name == '': sublime.status_message('CANNOT RENAME TO EMPTY IDENTIFIER') return cmd = [ 'gorename', # '-v', '-offset', view.file_name() + ':#' + str(byte_offset), '-to', new_name ] if simulate: cmd.append('-d') cmd_output = run_tool(cmd) if not cmd_output: simulate = False view.window().new_file().run_command("show_refactor_result", { "result": cmd_output.decode('utf-8'), "is_diff": simulate })
def get_doc(cmd_wd, cmd_arg): # `go doc` (Go 1.5+) has different capabilities to `godoc`. cmd = [ 'go', 'doc', '-c', ] if cmd_arg: # Most of the interesting identifiers in the pseudo-package builtin are # considered unexported because they start with lowercase. if cmd_arg == 'builtin' or cmd_arg.startswith('builtin.'): cmd.append('-u') cmd.append(cmd_arg) try: cmd_output = run_tool(cmd, wd=cmd_wd) except: sublime.status_message('FAILED: ' + ' '.join(cmd)) return return cmd_output.decode('utf-8')
def run(self, args): view = self.view # Show the stdlib documentation on the official site? default_docs = False non_empty_selections = [sl for sl in view.sel() if not sl.empty()] if len(non_empty_selections) == 0: default_docs = True if len(non_empty_selections) == 1: pkg = view.substr(non_empty_selections[0]) pkg = pkg.strip(' \t\r\n"') elif len(non_empty_selections) > 1: sublime.status_message('TOO MANY SELECTIONS') return launcher = 'xdg-open' via_shell = False if sys.platform == 'darwin': launcher = 'open' elif sys.platform == 'win32': launcher = 'start' via_shell=True if default_docs: run_tool([launcher, 'https://golang.org/pkg/'], wd='.', shell=via_shell) else: run_tool([launcher, 'https://godoc.org/' + pkg.lower()], wd='.', shell=via_shell)
def run(self, edit): try: settings = sublime.load_settings(SETTINGS_FILE) syntax_current_file = self.view.settings().get("syntax") enable_for_syntaxes = settings.get(ENABLE_FOR_SYNTAXES_LIST_SETTING, []) if syntax_current_file not in enable_for_syntaxes: enable_for_syntaxes.append(syntax_current_file) enable_for_syntaxes.sort() settings.set(ENABLE_FOR_SYNTAXES_LIST_SETTING, enable_for_syntaxes) sublime.save_settings(SETTINGS_FILE) msg = "Syntax added to the syntax list" sublime.status_message(msg) else: msg = "Syntax already in the syntax list" sublime.status_message(msg) except Exception: msg = "The SingleTrailingNewLine.sublime-settings file is invalid" sublime.status_message(msg)
def run(self, edit): try: settings = sublime.load_settings(SETTINGS_FILE) syntax_current_file = self.view.settings().get("syntax") enable_for_syntaxes = settings.get(ENABLE_FOR_SYNTAXES_LIST_SETTING, []) if syntax_current_file in enable_for_syntaxes: enable_for_syntaxes.remove(syntax_current_file) enable_for_syntaxes.sort() settings.set(ENABLE_FOR_SYNTAXES_LIST_SETTING, enable_for_syntaxes) sublime.save_settings(SETTINGS_FILE) msg = "Syntax removed from the syntax list" sublime.status_message(msg) else: msg = "Syntax was not in the syntax list" sublime.status_message(msg) except Exception: msg = "The SingleTrailingNewLine.sublime-settings file is invalid" sublime.status_message(msg)
def run(self, edit, dirs): settings = sublime.load_settings('dired.sublime-settings') for key_name in ['reuse_view', 'bookmarks']: settings.set(key_name, settings.get(key_name)) bm = bookmarks() for path in dirs : bm.append(path) settings.set('bookmarks', bm) # This command makes/writes a sublime-settings file at Packages/User/, # and doesn't write into one at Packages/dired/. sublime.save_settings('dired.sublime-settings') sublime.status_message('Bookmarking succeeded.') self.view.erase_regions('marked')
def run(self, edit): settings = sublime.load_settings('dired.sublime-settings') for key_name in ['reuse_view', 'bookmarks']: settings.set(key_name, settings.get(key_name)) bm = bookmarks() def on_done(select) : if not select == -1 : bm.pop(select) sublime.status_message('Remove selected bookmark.') settings.set('bookmarks', bm) sublime.save_settings('dired.sublime-settings') self.view.window().show_quick_panel(bm, on_done)
def run(self, command_line=''): assert command_line, 'expected non-empty command line' parsed = parse_command_line(command_line) # TODO: implement this if parsed.command.forced: show_not_implemented() return if self._view.is_read_only(): sublime.status_message("Can't write a read-only buffer.") return if not self._view.file_name(): sublime.status_message("Can't save a file without name.") return self.window.run_command('save') self.window.run_command('ex_quit', {'command_line': 'quit'})
def run(self, command_line=''): assert command_line, 'expected non-empty command line' parsed = parse_command_line(command_line) option = parsed.command.option value = parsed.command.value if option.endswith('?'): show_not_implemented() return try: set_local(self._view, option, value) except KeyError: sublime.status_message("Vintageuos: No such option.") except ValueError: sublime.status_message("Vintageous: Invalid value for option.")
def run(self, command_line=''): assert command_line, 'expected non-empty command line' parsed = parse_command_line(command_line) option = parsed.command.option value = parsed.command.value print (locals()) if option.endswith('?'): show_not_implemented() return try: set_global(self._view, option, value) except KeyError: sublime.status_message("Vintageuos: No such option.") except ValueError: sublime.status_message("Vintageous: Invalid value for option.")
def run(self, edit, insert=False, next_mode=None): def on_done(s): state = State(self.view) try: rv = [str(eval(s, None, None)),] if not insert: state.registers[REG_EXPRESSION] = rv else: self.view.run_command('insert_snippet', {'contents': str(rv[0])}) state.reset() except: sublime.status_message("Vintageous: Invalid expression.") on_cancel() def on_cancel(): state = State(self.view) state.reset() self.view.window().show_input_panel('', '', on_done, None, on_cancel)
def run(self): settings = SharedFunctions.get_package_settings() if settings: path = settings.get("docs_path", None) if path and os.path.isdir(path): scraped_api = scrape_api(path) if scraped_api: SharedFunctions.write_resource_file("The Subliming of Isaac.json", scraped_api) completions = generate_completions(scraped_api, settings.get("completions_scope", "source.lua")) if completions: SharedFunctions.write_resource_file("The Subliming of Isaac.sublime-completions", completions) sublime.status_message("Finished scraping Afterbirth+ API...") else: if not path: SharedFunctions.error_message("'docs_path' setting is undefined.") else: SharedFunctions.error_message( "The value of the 'docs_path' setting is not a path to an existing directory.")
def run(self, i): if not self.thread.is_alive(): if hasattr(self.thread, 'result') and not self.thread.result: sublime.status_message('') return 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)
def _log(message, *args, status=False, dialog=False): """ A simple logic facility to ensure that all console output is prefixed with the package name so the source is clear. Can also optionally send the output to the status line and/or a message dialog. """ message = message % args print("HyperHelp:", message) if status: sublime.status_message(message) if dialog: sublime.message_dialog(message)
def status_message(self, text): sublime.status_message("%s: %s" % (self.package_name, text))
def stop(self): sublime.status_message(self.success_message) self.stopped = True
def _render_impl(self, pfile, view, message): sublime.status_message(message.split('\n')[0])
def _clean_impl(self, pfile, view): if pfile.showing_arguments: sublime.status_message("")
def init_addon(self, path): """ scan addon folder and parse skin content etc """ self.addon = None addon_xml = os.path.join(path, "addon.xml") if os.path.exists(addon_xml): logging.info("Kodi project detected: " + addon_xml) self.addon = Addon.by_project(path, self.settings) # sublime.status_message("KodiDevKit: successfully loaded addon")
def checkout(filename, prefs): output = BGS_Perforce.checkout(prefs["workspace"], filename) sublime.status_message(output) # Creates a directory for our cache files, if necessary, in the OS's temporary folder # We don't use the temporary directory creation tools Python supplies because we want the folder to stay the same # between runs so we can continue to access it.