我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sublime.active_window()。
def blink(times=4, delay=55): prefs = load_settings('Preferences.sublime-settings') if prefs.get('vintageous_visualbell') is False: return v = active_window().active_view() settings = v.settings() # Ensure we leave the setting as we found it. times = times if (times % 2) == 0 else times + 1 def do_blink(): nonlocal times if times > 0: settings.set('highlight_line', not settings.get('highlight_line')) times -= 1 set_timeout(do_blink, delay) do_blink()
def run(self): sublime.run_command('new_window') new_window = sublime.active_window() new_window.run_command('set_layout', { 'cols': [0.0, 0.5, 1.0], 'rows': [0.0, 1.0], 'cells': [[0, 0, 1, 1], [1, 0, 2, 1]] }) new_window.focus_group(0) edit_view = new_window.new_file() edit_view_settings = edit_view.settings() edit_view_settings.set('minihtml_preview_edit_view', True) edit_view.set_scratch(True) edit_view.set_syntax_file('Packages/HTML/HTML.sublime-syntax') # Unfortunately Sublime indents on 'insert' edit_view.settings().set('auto_indent', False) edit_view.run_command('insert', {'characters': template}) edit_view.settings().set('auto_indent', True) new_window.focus_group(1) output_view = new_window.new_file() output_view.set_scratch(True) edit_view_settings.set('minihtml_preview_output_view_id', output_view.id()) new_window.focus_group(0)
def help_view(window=None): """ Find and return the help view for the provided window. If no window is provided, the currently active window is checked instead. The return value is the view on success or None if there is currently no help view in the window. """ window = window if window is not None else sublime.active_window() view = find_view(window, "HyperHelp") if view is not None: settings = view.settings() if settings.has("_hh_package") and settings.has("_hh_file"): return view return None
def on_api_ready(): global api_ready api_ready = True for m in list(sys.modules.values()): if "plugin_loaded" in m.__dict__: try: m.plugin_loaded() except: traceback.print_exc() # Synthesize an on_activated call w = sublime.active_window() if w: view_id = sublime_api.window_active_view(w.window_id) if view_id != 0: try: on_activated(view_id) except: traceback.print_exc()
def wait_for_open(self, dest): """Wait for new linter window to open in another thread.""" def open_linter_py(): """Wait until the new linter window has opened and open linter.py.""" start = datetime.datetime.now() while True: time.sleep(0.25) delta = datetime.datetime.now() - start # Wait a maximum of 5 seconds if delta.seconds > 5: break window = sublime.active_window() folders = window.folders() if folders and folders[0] == dest: window.open_file(os.path.join(dest, 'linter.py')) break sublime.set_timeout_async(open_linter_py, 0)
def plugin_loaded(): """The ST3 entry point for plugins.""" persist.plugin_is_loaded = True persist.settings.load() persist.printf('debug mode:', 'on' if persist.debug_mode() else 'off') util.create_tempdir() for linter in persist.linter_classes.values(): linter.initialize() plugin = SublimeLinter.shared_plugin() queue.start(plugin.lint) util.generate_menus() util.generate_color_scheme(from_reload=False) persist.settings.on_update_call(SublimeLinter.on_settings_updated) # This ensures we lint the active view on a fresh install window = sublime.active_window() if window: plugin.on_activated(window.active_view())
def run(self, edit, **args): data = run_command(self.view, {"type": "definition", "lineCharPositions": True}) if data is None: return file = data.get("file", None) if file is not None: # Found an actual definition row, col = self.view.rowcol(self.view.sel()[0].b) cur_pos = self.view.file_name() + ":" + str(row + 1) + ":" + str(col + 1) jump_stack.append(cur_pos) if len(jump_stack) > 50: jump_stack.pop(0) real_file = (os.path.join(get_pfile(self.view).project.dir, file) + ":" + str(data["start"]["line"] + 1) + ":" + str(data["start"]["ch"] + 1)) sublime.active_window().open_file(real_file, sublime.ENCODED_POSITION) else: url = data.get("url", None) if url is None: sublime.error_message("Could not find a definition") else: webbrowser.open(url)
def run(self, edit): for region in self.view.sel(): if not region.empty(): self.view.insert(edit, region.begin(), self.view.substr(region)) continue line_contents = self.view.substr(self.view.line(region)) match = re.search(r'File "(.*?)", line (\d*), in .*', line_contents) if match: sublime.active_window().open_file("{}:{}".format(os.path.realpath(match.group(1)), match.group(2)), sublime.ENCODED_POSITION) return match = re.search(r"', \('(.*?)', (\d+), (\d+), ", line_contents) if match: sublime.active_window().open_file("{}:{}:{}".format(os.path.realpath(match.group(1)), match.group(2), match.group(3)), sublime.ENCODED_POSITION) return
def run(self, edit): flags = sublime.CLASS_WORD_START | sublime.CLASS_WORD_END path = utils.get_node_content(self.view, flags) imagepath = INFOS.addon.translate_path(path) if not os.path.exists(imagepath): return None if os.path.isdir(imagepath): self.files = [] for (_dirpath, _dirnames, filenames) in os.walk(imagepath): self.files.extend(filenames) break self.files = [imagepath + s for s in self.files] else: self.files = [imagepath] sublime.active_window().show_quick_panel(items=self.files, on_select=self.on_done, selected_index=0, on_highlight=self.show_preview)
def run(self, edit): self.label_ids = [] self.labels = [] region = self.view.sel()[0] if region.begin() == region.end(): logging.critical("Please select the complete label") return False word = self.view.substr(region) for po_file in INFOS.get_po_files(): for entry in po_file: if entry.msgid.lower() == word.lower() and entry.msgctxt not in self.label_ids: self.label_ids.append(entry.msgctxt) self.labels.append(["%s (%s)" % (entry.msgid, entry.msgctxt), entry.comment]) self.labels.append("Create new label") sublime.active_window().show_quick_panel(items=self.labels, on_select=lambda s: self.on_done(s, region), selected_index=0)
def run_async(self): result = None try: result = CLI(self.view).get_def() except InvalidContext: print('Invalid context') pass except Exception as e: display_unknown_error(self.view, e) return print(result) if not result or not result.get('path'): return sublime.active_window().open_file( result['path'] + ':' + str(result['line']) + ':' + str(result['start']), sublime.ENCODED_POSITION | sublime.TRANSIENT )
def handle_diagnostics(update: 'Any'): util.debug('handling diagnostics') file_path = util.uri_to_filename(update.get('uri')) window = sublime.active_window() if not util.is_apex_file(window.active_view()): util.debug("Skipping diagnostics for file", file_path, " it is not in the workspace") return diagnostics = list( Diagnostic.from_lsp(item) for item in update.get('diagnostics', [])) view = window.find_open_file(file_path) # diagnostics = update.get('diagnostics') update_diagnostics_in_view(view, diagnostics) # update panel if available origin = 'dxmate' # TODO: use actual client name to be able to update diagnostics per client update_file_diagnostics(window, file_path, origin, diagnostics)
def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:visualforce:page:create', '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\nVisaulforce page created') file = os.path.join(self.class_dir, self.page_name + '.page') sublime.active_window().open_file(file) else: printer.write('\nError creating Visualforce page:') printer.write('\n' + str(err, 'utf-8'))
def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:component:create', '-n', self.cmp_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\nLightning Component created') file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp') sublime.active_window().open_file(file) else: printer.write('\nError creating Lightning Component:') printer.write('\n' + str(err, 'utf-8'))
def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:test:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\nLightning Test created') file = os.path.join(self.class_dir, self.event_name + '.resource') sublime.active_window().open_file(file) else: printer.write('\nError creating Lightning Test:') printer.write('\n' + str(err, 'utf-8'))
def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:interface:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\nLightning Interface created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf') sublime.active_window().open_file(file) else: printer.write('\nError creating Lightning Interface:') printer.write('\n' + str(err, 'utf-8'))
def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:event:create', '-n', self.event_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\nLightning Event created') file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt') sublime.active_window().open_file(file) else: printer.write('\nError creating Lightning Event:') printer.write('\n' + str(err, 'utf-8'))
def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:lightning:app:create', '-n', self.app_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\nLightning App created') file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app') sublime.active_window().open_file(file) else: printer.write('\nError creating Lightning App:') printer.write('\n' + str(err, 'utf-8'))
def run_command(self): dx_folder = util.dxProjectFolder() args = ['sfdx', 'force:apex:class:create', '-n', self.class_name, '-d', self.class_dir] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder) p.wait() out, err = p.communicate() r = p.returncode if p.returncode == 0: printer.write('\nApex class created') file = os.path.join(self.class_dir, self.class_name + '.cls') sublime.active_window().open_file(file) else: printer.write('\nError creating Apex Class:') printer.write('\n' + str(err, 'utf-8'))
def run(self, edit, event): if self.symbol_details: view_path = self.symbol_details[0] focus_region = self.symbol_details[1] # collapse the region to a single point, the region start focus_region = sublime.Region(focus_region.begin(), focus_region.begin()) # get the view with this path view = sublime.active_window().find_open_file(view_path) if view: self.showSymbol(view, focus_region) else: # weird issue, but unless we open the file with 'ENCODED_POSITION' it won't scroll afterwards # https://github.com/SublimeTextIssues/Core/issues/538 view = sublime.active_window().open_file("%s:%d:%d" % (view_path, 1, 0), sublime.ENCODED_POSITION) def viewLoadedTimeout(): # we can run methods only on loaded views if not view.is_loading(): self.showSymbol(view, focus_region) else: sublime.set_timeout(viewLoadedTimeout, 100) # open is asynchronous, wait for a bit and then try to focus sublime.set_timeout(viewLoadedTimeout, 100)
def mm_project_directory(window=None): if window == None: window = sublime.active_window() folders = window.folders() if len(folders) > 0: return window.folders()[0] # def get_project_settings(window=None): # if window == None: # window = sublime.active_window() # try: # return parse_json_from_file(os.path.join(window.folders()[0],"config",".settings")) # except: # # raise BaseException("Could not load project settings") # print("Could not load project settings")
def run(self, edit): settings = setting.load() self.settings = settings projects = settings["projects"] default_project = settings["default_project"] dirs = [] dirs_result = [] for project_key in projects.keys(): project_value = projects[project_key] if default_project == project_key: tmp = '[?]' + project_key else: tmp = '[X]' + project_key dirs.append(tmp) dirs_result.append(project_key) self.results = dirs_result window = sublime.active_window() window.show_quick_panel(dirs, self.panel_done, sublime.MONOSPACE_FONT)
def plugin_loaded(): global currentSettings, language, currentView currentSettings = sublime.load_settings(setting_file) language = currentSettings.get('language') currentView = sublime.active_window().active_view() docphpPath = getDocphpPath() if not os.path.isdir(docphpPath + 'language'): os.makedirs(docphpPath + 'language') if not callable(sublime_symbol.symbol_at_point) or not callable(sublime_symbol.navigate_to_symbol): sublime.error_message('Cannot find symbol_at_point from Default.sublime-package\n\nPlease restore the file which usually replaced by outdated localizations') from package_control import events if events.install(package_name) or not language: currentView.run_command('docphp_checkout_language', {"is_init": True, "set_fallback": True})
def run(self, edit): # get the cursor point sel = self.view.sel()[0] # get the current scope by cursor position current_scope = self.view.scope_name(sel.begin()) # print(current_file_source) tooltip_files_arr = self.get_tooltip_files(current_scope) # get user selection sel = self.get_user_selection(sel) # do match with user selection and return the result results = self.match_selection(sel, tooltip_files_arr) # print("len results: " + str(len(results))) for result in results: # get the correct link if there is link = self.has_link(result) # edit the result in html for tooltip window html_tooltip = Utilities.result_format(result['json_result'], self.keyorder, link) self.results_arr.append(html_tooltip) names = self.get_file_names(results) # print("len results_arr: " + str(len(self.results_arr))) if len(self.results_arr) == 1: self.show_popup_with_timeout(self.results_arr[0]) elif len(self.results_arr) > 1: sublime.active_window().show_quick_panel(names, self.on_done, sublime.MONOSPACE_FONT)
def get_project_dir(): view = sublime.active_window().active_view() if not view: return None fn = view.file_name() if not fn: return None fn = normalize(fn) folders = sublime.active_window().folders() if not folders: return None for folder in folders: if fn.startswith(folder + os.sep): return folder return None
def get_setting(key, default=None, view=None): return gdb_settings.get(key, default) try: if view is None: view = sublime.active_window().active_view() s = view.settings() # Try executable specific settings first if exec_settings and key in exec_settings: return exec_settings[key] # Then try user settings if s.has("sublimegdb_%s" % key): return s.get("sublimegdb_%s" % key) except: pass # Default settings return sublime.load_settings("SublimeGDB.sublime-settings").get(key, default)
def update_view_markers(view=None): if view is None: view = sublime.active_window().active_view() fn = view.file_name() if fn is not None: fn = normalize(fn) pos_scope = get_setting("position_scope", "entity.name.class") pos_icon = get_setting("position_icon", "bookmark") cursor = [] if fn == gdb_cursor and gdb_cursor_position != 0: cursor.append(view.full_line(view.text_point(gdb_cursor_position - 1, 0))) global gdb_last_cursor_view if gdb_last_cursor_view is not None: gdb_last_cursor_view.erase_regions("sublimegdb.position") gdb_last_cursor_view = view view.add_regions("sublimegdb.position", cursor, pos_scope, pos_icon, sublime.HIDDEN) gdb_callstack_view.update_marker(pos_scope, pos_icon) gdb_threads_view.update_marker(pos_scope, pos_icon) gdb_breakpoint_view.update_marker(view)
def create_view(self, errors): if not self.view: self.view = sublime.active_window().new_file() self.view.set_name(self.name) self.view.set_scratch(True) self.view.set_read_only(True) # Setting command_mode to false so that vintage # does not eat the "enter" keybinding self.view.settings().set('command_mode', False) self.closed = False self.view.run_command("error_view_clear") self.lines = "" self.end = -1 for e in errors: self.add_line(e) self.view.run_command("error_view_add_line", {"line": self.lines, "doScroll": True})
def run(self, index=None, **args): command = args.get('command') active_file_path = self.__active_file_path() active_folders = sublime.active_window().folders() if command == 'mlist': self.__beagle = Phoenix(active_file_path + 'beagle_migrations', self.__patterns(), active_folders) self.window.show_quick_panel(self.__beagle.descriptions(), self.__open_file) else: if not active_folders: active_folders = os.path.split(active_file_path)[0] sublime.error_message("SideBar is empty!") if active_file_path: if self.__patterns(): self.__beagle = Phoenix(active_file_path, self.__patterns(), active_folders) self.window.show_quick_panel(self.__beagle.descriptions(), self.__open_file) else: self.__status_msg("Patterns are not loaded!") else: self.__status_msg("No open files")
def run(self): self.window = sublime.active_window() for view in self.window.views(): self.view = view if not self.will_closing_discard(view): continue self.last_focused_view = self.window.active_view() self.window.focus_view(view) self.show_discard_prompt() return # wait for input, then start over self.window.run_command('close_window')
def ensure_reload(): """ Ensure all modules reload to initialize plugin successfully. """ start_upgrade_msg = "Do not close the Sublime Text. Upgrading {}".format( PACKAGE_NAME ) finish_upgrade_msg = "{} upgrade finished.".format(PACKAGE_NAME) active_view = sublime.active_window().active_view() active_view.set_status("afi_status", start_upgrade_msg) def erase_status(): active_view.erase_status("afi_status") def reload(): sublime.run_command("afi_reload") active_view.set_status("afi_status", finish_upgrade_msg) sublime.set_timeout(erase_status, 2000) sublime.set_timeout_async(reload, 5000)
def set_status(self): '''Update status-bar; self.show_hidden must be assigned before call it''' # if view isnot focused, view.window() may be None window = self.view.window() or sublime.active_window() path_in_project = any(folder == self.path[:-1] for folder in window.folders()) settings = self.view.settings() copied_items = settings.get('outline_to_copy', []) cut_items = settings.get('outline_to_move', []) status = u" ?? [?: Help] {0}Hidden: {1}{2}{3}".format( 'Project root, ' if path_in_project else '', 'On' if self.show_hidden else 'Off', ', copied(%d)' % len(copied_items) if copied_items else '', ', cut(%d)' % len(cut_items) if cut_items else '' ) self.view.set_status("__FileBrowser__", status)
def get_usages_in_files(subject, files): """ Smart approach: reads files from a list and parses them. """ usage_list = [] for file_path in files: try: usages = get_usages_in_file(file_path, subject) usage_list.extend(usages) except UnicodeDecodeError: utils.log("Failed to open file", file_path, warning=True) except FileNotFoundError: utils.log("File not found", file_path, warning=True) utils.log("Probably the file has been (re)moved and the dependency graph is stale. Please rebuild!", warning=True) sublime.active_window().status_message("GotoUsage Error! Dependency graph looks out of date. Please rebuild!") return usage_list
def confirm(self, paths, in_parent, data, key): import functools window = sublime.active_window() window.show_input_panel("BUG!", '', '', None, None) window.run_command('hide_panel'); yes = [] yes.append('Yes, Replace the following items:'); for item in data: yes.append(SideBarItem(item, os.path.isdir(item)).pathWithoutProject()) no = [] no.append('No'); no.append('Continue without replacing'); while len(no) != len(yes): no.append('ST3 BUG'); window.show_quick_panel([yes, no], functools.partial(self.on_done, paths, in_parent, key))
def confirm(self, paths, display_paths): import functools window = sublime.active_window() window.show_input_panel("BUG!", '', '', None, None) window.run_command('hide_panel'); yes = [] yes.append('Yes, delete the selected items.'); for item in display_paths: yes.append(item); no = [] no.append('No'); no.append('Cancel the operation.'); while len(no) != len(yes): no.append(''); if sublime.platform() == 'osx': sublime.set_timeout(lambda:window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths)), 200); else: window.show_quick_panel([yes, no], functools.partial(self.on_confirm, paths))
def on_plugin_loaded(self): """Call upon plugin load event.""" # init settings manager self.loaded = True log.debug("handle plugin loaded") EasyClangComplete.settings_manager = SettingsManager() # self.on_settings_changed() EasyClangComplete.settings_manager.add_change_listener( self.on_settings_changed) self.on_settings_changed() # init view config manager EasyClangComplete.view_config_manager = ViewConfigManager() # As the plugin has just loaded, we might have missed an activation # event for the active view so completion will not work for it until # re-activated. Force active view initialization in that case. self.on_activated_async(sublime.active_window().active_view())
def run(self, edit, **args): try: path = args.get('paths', [])[0] if os.path.isfile(path): path = os.path.dirname(path) view = sublime.active_window().active_view() if check_syntax(view): disp_msg('base directory of current log is set as : ' + path) self.view.settings().set('result_base_dir', path) global smry_view if smry_view is not None: smry_view.settings().set('result_base_dir', path) # save to project prj = view.window().project_file_name() if prj != "": pdata = view.window().project_data() pdata['base_dir'] = path view.window().set_project_data(pdata) pass except Exception: disp_exept()
def handle_diagnostics(update: 'Any'): file_path = uri_to_filename(update.get('uri')) window = sublime.active_window() if not is_in_workspace(window, file_path): debug("Skipping diagnostics for file", file_path, " it is not in the workspace") return diagnostics = list( Diagnostic.from_lsp(item) for item in update.get('diagnostics', [])) origin = 'lsp' # TODO: use actual client name to be able to update diagnostics per client update_file_diagnostics(window, file_path, origin, diagnostics) Events.publish("document.diagnostics", DiagnosticsUpdate(file_path, diagnostics)) # TODO: expose updates to features
def start_active_views(): window = sublime.active_window() if window: views = list() # type: List[sublime.View] num_groups = window.num_groups() for group in range(0, num_groups): view = window.active_view_in_group(group) if is_supported_view(view): if window.active_group() == group: views.insert(0, view) else: views.append(view) if len(views) > 0: first_view = views.pop(0) debug('starting active=', first_view.file_name(), 'other=', len(views)) initialize_on_open(first_view) if len(views) > 0: for view in views: didopen_after_initialize.append(view)
def _load_css_themes(self) -> None: """ Load any css theme found in the anaconda CSS themes directory or in the User/Anaconda.themes directory """ css_files_pattern = os.path.join( os.path.dirname(__file__), os.pardir, 'css', '*.css') for css_file in glob.glob(css_files_pattern): logging.info('anaconda: {} css theme loaded'.format( self._load_css(css_file)) ) packages = sublime.active_window().extract_variables()['packages'] user_css_path = os.path.join(packages, 'User', 'Anaconda.themes') if os.path.exists(user_css_path): css_files_pattern = os.path.join(user_css_path, '*.css') for css_file in glob.glob(css_files_pattern): logging.info( 'anaconda: {} user css theme loaded', self._load_css(css_file) )
def scroll_into_view(self): try: view = sublime.active_window().active_view() # TODO(guillermooo): Maybe some commands should show their # surroundings too? # Make sure we show the first caret on the screen, but don't show # its surroundings. view.show(view.sel()[0], False) except: pass
def _run_parser_via_panel(self, command): """ Return `True` if the current parser needs to be run via a panel. If needed, it runs the input-panel-based parser. """ if command.input_parser.type == input_types.VIA_PANEL: if self.non_interactive: return False sublime.active_window().run_command(command.input_parser.command) return True return False
def _run(): _logger.debug('run \'%s\'', file_name()) try: window = sublime.active_window() with _open(file_name(), 'r') as f: for line in f: cmd, args = _parse_line(line) if cmd: _logger.debug('run command \'%s\' with args %s', cmd, args) window.run_command(cmd, args) except FileNotFoundError: _logger.debug('rcfile not found')
def show_toc(self, pkg_info, items, stack): captions = [[item["caption"], item["topic"] + (" ({} topics)".format(len(item["children"])) if "children" in item else "")] for item in items] if len(captions) == 0 and len(stack) == 0: return log("No help topics defined for %s", pkg_info.package, status=True) if len(stack) > 0: captions.insert(0, ["..", "Go back"]) sublime.active_window().show_quick_panel( captions, on_select=lambda index: self.select_toc_item(pkg_info, items, stack, index))
def select_package(self): help_list = help_index_list() if len(help_list) <= 1: return log("No packages with help are currently installed", status=True) pkg_list = sorted([key for key in help_list]) captions = [[help_list[key].package, help_list[key].description] for key in pkg_list] sublime.active_window().show_quick_panel( captions, on_select=lambda index: self.select_package_item(captions, index))
def project_path(): project_data = sublime.active_window().project_data() # if cannot find project data, use cwd if project_data is None: return os.getcwd() folders = project_data['folders'] folder_path = folders[0]['path'] return folder_path
def get_pref(key): global_settings = sublime.load_settings(SETTINGS_FILE) value = global_settings.get(key) # Load active project settings project_settings = sublime.active_window().active_view().settings() # Overwrite global config value if it's defined if project_settings.has(PROJECT_NAME): value = project_settings.get(PROJECT_NAME).get(key, value) return value
def normalize_path(path, realpath=False): if realpath: return os.path.realpath(os.path.expanduser(path)) else: project_dir = sublime.active_window().project_file_name() if project_dir: cwd = os.path.dirname(project_dir) else: cwd = os.getcwd() return os.path.normpath(os.path.join(cwd, os.path.expanduser(path))) # Yield path and every directory above path.
def on_api_ready(): global api_ready api_ready = True for m in list(sys.modules.values()): if "plugin_loaded" in m.__dict__: try: m.plugin_loaded() except: traceback.print_exc() # Synthesize an on_activated call w = sublime.active_window() if w: view_id = sublime_api.window_active_view(w.window_id) if view_id != 0: try: on_activated(view_id) except: traceback.print_exc() # Create ViewEventListener instances if len(view_event_listener_classes) > 0: for w in sublime.windows(): for v in w.views(): attach_view(v)