我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sublime.windows()。
def find_executable(executable): """ Return the path to the given executable, or None if not found. create_environment is used to augment PATH before searching for the executable. """ env = create_environment() for base in env.get('PATH', '').split(os.pathsep): path = os.path.join(os.path.expanduser(base), executable) # On Windows, if path does not have an extension, try .exe, .cmd, .bat if sublime.platform() == 'windows' and not os.path.splitext(path)[1]: for extension in ('.exe', '.cmd', '.bat'): path_ext = path + extension if can_exec(path_ext): return path_ext elif can_exec(path): return path return None
def on_pre_close(self, view): if view.file_name() is None: return window = view.window() this_project_path = find_project_dir(view) def perform(): all_views = [view for win in sublime.windows() for view in win.views()] all_project_paths = [find_project_dir(v) for v in all_views] all_project_paths = [p for p in all_project_paths if p is not None] all_project_paths = list(set(all_project_paths)) if this_project_path not in all_project_paths: stop_server(this_project_path) window.status_message('Closed server for path:' + this_project_path) # delay server closing for 0.5s, because we may be "switching" between files sublime.set_timeout(perform, 500)
def clean_temp_folder(): tmp_files = os.listdir(TMP_DIR) for win in sublime.windows(): for view in win.views(): file_name = view.file_name() tmp_name = get_temp_name(file_name) if tmp_name in tmp_files: if not view.is_dirty(): tmp_file = os.path.join(TMP_DIR, tmp_name) # check mtime mtime1 = os.path.getmtime(file_name) mtime2 = os.path.getmtime(tmp_file) if mtime1 != mtime2: # file was changed outside view.settings().erase('prevent_detect') continue shutil.move(tmp_file, file_name) tmp_files.remove(tmp_name) for tmp_name in tmp_files: tmp_file = os.path.join(TMP_DIR, tmp_name) os.unlink(tmp_file)
def run(self): for win in sublime.windows(): self.window = win 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 sublime.run_command('exit') # # Rest of the commands #
def is_hidden(self, filename, path, goto=''): if not (path or goto): # special case for ThisPC return False tests = self.view.settings().get('outline_hidden_files_patterns', ['.*']) if isinstance(tests, str): tests = [tests] if any(fnmatch.fnmatch(filename, pattern) for pattern in tests): return True if sublime.platform() != 'windows': return False # check for attribute on windows: try: attrs = ctypes.windll.kernel32.GetFileAttributesW(join(path, goto, filename)) assert attrs != -1 result = bool(attrs & 2) except (AttributeError, AssertionError): result = False return result
def run(self, paths = [], application = "", extensions = "", args=[]): application_dir, application_name = os.path.split(application) if extensions == '*': extensions = '.*' if extensions == '': items = SideBarSelection(paths).getSelectedItems() else: items = SideBarSelection(paths).getSelectedFilesWithExtension(extensions) import subprocess try: for item in items: if sublime.platform() == 'osx': subprocess.Popen(['open', '-a', application] + args + [item.name()], cwd=item.dirname()) elif sublime.platform() == 'windows': subprocess.Popen([application_name] + args + [escapeCMDWindows(item.path())], cwd=expandVars(application_dir), shell=True) else: subprocess.Popen([application_name] + args + [escapeCMDWindows(item.name())], cwd=item.dirname()) except: sublime.error_message('Unable to "Open With..", probably incorrect path to application.')
def plugin_loaded(): """ plugin_loaded """ # from default/user settings get_severity_list() # register callback lhs = get_prefs() lhs.clear_on_change('lh-prefs') lhs.add_on_change('lh-prefs', plugin_loaded) # check all log-highlited views wins_l = sublime.windows() global logh_view for w in wins_l: view_l = w.views() for v in view_l: if check_syntax(v): logh_view.append([v.id(), 0]) if v.settings().get('logh_lastv') is True: global logh_lastv logh_lastv = v.id()
def open(self, view): """ Should be called if a new view is opened, and this view belongs to the same tsconfig.json file """ if view not in self.views: Debug('project+', "View %s added to project %s" % (view.file_name(), self.tsconfigfile)) self.views.append(view) view.settings().set('auto_complete', self.get_setting("auto_complete")) view.settings().set('extensions', ['ts']) window = view.window() if window is None: Debug('notify', "ArcticTypescript: Window is None, why??") return if window not in self.windows: Debug('project+', "New Window added to project %s" % (self.tsconfigfile, )) self.windows.append(view.window())
def highlight_all_open_files(self): """ update hightlights (red underline) in all files, using the errors in project """ self.errors = {} # iterate through all open views, to remove all remaining outdated underlinings for window in sublime.windows(): for view in window.views(): if is_ts(view): error_regions, warning_regions, error_texts = \ self.project.errors.tssjs_to_highlighter(view) self.errors[fn2k(view.file_name())] = error_texts # apply regions, even if empty (that will remove every highlight in that file) view.add_regions('typescript-error' , error_regions , 'invalid' , self.error_icon, self.underline) view.add_regions('typescript-warnings' , warning_regions , 'invalid' , self.warning_icon, self.underline)
def on_request(self, request): if len(sublime.windows()) == 0 or self.new_window_on_connect: sublime.run_command('new_window') if len(self.window_command_on_connect) > 0: sublime.active_window().run_command(self.window_command_on_connect) web_socket_server_thread = WebSocketServerThread(self._settings) web_socket_server_thread.start() while not web_socket_server_thread.get_server().get_running(): sleep(0.1) port = web_socket_server_thread.get_server().get_port() Utils.show_status('Connection opened') return Response(json.dumps({"WebSocketPort": port, "ProtocolVersion": 1}), "200 OK", {'Content-Type': 'application/json'})
def clear_local_caches(): files = [] roots = set() for window in sublime.windows(): # All views in a window share the same settings. view = window.views()[0] cwd = s_cwd(view) local_root = File.local_root_for_cwd(cwd) roots.add(local_root) for root in roots: log('Deleting local cache directory [{0}]...'.format(root)) if os.path.exists(root): shutil.rmtree(root) for file in files: log("Refreshing open file [{0}]...".format(file.remote_path())) download_file(file)
def _cleanup_views(): # Resets cursor and mode. In the case of errors loading the plugin this can # help prevent the normal functioning of editor becoming unusable e.g. the # cursor getting stuck in a block shape or the mode getting stuck in normal # or visual mode. for window in sublime.windows(): for view in window.views(): settings = view.settings() settings.set('command_mode', False) settings.set('inverse_caret_state', False) # TODO should the "vintage" setting be erased too? i.e. v.settings().erase('vintage')
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)
def check_all_view_event_listeners(): global check_all_view_event_listeners_scheduled check_all_view_event_listeners_scheduled = False for w in sublime.windows(): for v in w.views(): check_view_event_listeners(v)
def run(self, string, current_window_only=True): """ Send a string Args: string (str): string of characters to send current_window_only (bool, optional): constrain terminal search to the current ST window only """ if current_window_only: windows = [self.window] else: windows = sublime.windows() term_view = None for w in windows: for v in w.views(): term_view = TerminalViewManager.load_from_id(v.id()) if term_view is not None: group, index = w.get_view_index(v) active_view = w.active_view_in_group(group) if active_view == v: break if term_view is None: utils.ConsoleLogger.log("No terminal found") return term_view.send_string_to_shell(string)
def create_tempdir(): """Create a directory within the system temp directory used to create temp files.""" try: if os.path.isdir(tempdir): shutil.rmtree(tempdir) os.mkdir(tempdir) # Make sure the directory can be removed by anyone in case the user # runs ST later as another user. os.chmod(tempdir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) except PermissionError: if sublime.platform() != 'windows': current_user = pwd.getpwuid(os.geteuid())[0] temp_uid = os.stat(tempdir).st_uid temp_user = pwd.getpwuid(temp_uid)[0] message = ( 'The SublimeLinter temp directory:\n\n{0}\n\ncould not be cleared ' 'because it is owned by \'{1}\' and you are logged in as \'{2}\'. ' 'Please use sudo to remove the temp directory from a terminal.' ).format(tempdir, temp_user, current_user) else: message = ( 'The SublimeLinter temp directory ({}) could not be reset ' 'because it belongs to a different user.' ).format(tempdir) sublime.error_message(message) from . import persist persist.debug('temp directory:', tempdir)
def apply_to_all_views(callback): """Apply callback to all views in all windows.""" for window in sublime.windows(): for view in window.views(): callback(view) # misc utils
def load(self): Pref.view = False Pref.elapsed_time = 0.4 Pref.running = False Pref.wrdRx = re.compile(s.get('word_regexp', "^[^\w]?`*\w+[^\w]*$"), re.U) Pref.wrdRx = Pref.wrdRx.match Pref.splitRx = s.get('word_split', None) if Pref.splitRx: Pref.splitRx = re.compile(Pref.splitRx, re.U) Pref.splitRx = Pref.splitRx.findall Pref.enable_live_count = s.get('enable_live_count', True) Pref.enable_readtime = s.get('enable_readtime', False) Pref.enable_line_word_count = s.get('enable_line_word_count', False) Pref.enable_line_char_count = s.get('enable_line_char_count', False) Pref.enable_count_lines = s.get('enable_count_lines', False) Pref.enable_count_chars = s.get('enable_count_chars', False) Pref.enable_count_pages = s.get('enable_count_pages', True) Pref.words_per_page = s.get('words_per_page', 300) Pref.page_count_mode_count_words = s.get('page_count_mode_count_words', True) Pref.char_ignore_whitespace = s.get('char_ignore_whitespace', True) Pref.readtime_wpm = s.get('readtime_wpm', 200) Pref.whitelist = [x.lower() for x in s.get('whitelist_syntaxes', []) or []] Pref.blacklist = [x.lower() for x in s.get('blacklist_syntaxes', []) or []] Pref.strip = s.get('strip', []) for window in sublime.windows(): for view in window.views(): view.erase_status('WordCount'); view.settings().erase('WordCount')
def dxProjectFolder(self): for window in sublime.windows(): folder = self.get_dx_folder_for_window(window) if folder != '': return folder return ''
def plugin_loaded(): for win in sublime.windows(): for view in win.views(): initial(view)
def setup_views(): clean_temp_folder() # check existing views for win in sublime.windows(): for view in win.views(): if not get_setting(view, 'convert_on_load'): break view.settings().set('is_init_dirty_state', view.is_dirty()) if view.is_dirty() or view.settings().get('origin_encoding'): show_encoding_status(view) continue file_name = view.file_name() cnt = get_setting(view, 'max_detect_lines') threading.Thread(target=lambda: detect(view, file_name, cnt)).start()
def wait_for_ready(): if sublime.windows(): setup_views() else: sublime.set_timeout(wait_for_ready, 100)
def retarget_all_views(source, destination): if source[-1] != os.path.sep: source += os.path.sep if destination[-1] != os.path.sep: destination += os.path.sep for window in sublime.windows(): for view in window.views(): filename = view.file_name() if os.path.commonprefix([source, filename]) == source: view.retarget( os.path.join(destination, filename[len(source):]) )
def retarget_view(source, destination): source = os.path.normcase(os.path.abspath(source)) destination = os.path.normcase(os.path.abspath(destination)) for window in sublime.windows(): for view in window.views(): path = os.path.abspath(view.file_name()) if os.path.normcase(path) == source: view.retarget(destination)
def hijack_window(): '''Execute on loading plugin or on new window open; allow to open FB automatically in ST3 ''' settings = sublime.load_settings('outline.sublime-settings') command = settings.get("outline_hijack_new_window") if command: if command == "jump_list": sublime.set_timeout(lambda: sublime.windows()[-1].run_command("outline_jump_list"), 1) else: sublime.set_timeout(lambda: sublime.windows()[-1].run_command("outline", {"immediate": True}), 1)
def get_all_project_names(): "Return a list of all open project names" windows = sublime.windows() varses = [w.extract_variables() for w in windows] project_names = [v.get('project_base_name') for v in varses] return project_names
def window_set_status(key, name =''): for window in sublime.windows(): for view in window.views(): view.set_status('SideBar-'+key, name)
def _delete_threaded(self, paths): key = 'delete-'+str(time.time()) window_set_status(key, 'Deleting…') try: from .send2trash import send2trash for item in SideBarSelection(paths).getSelectedItemsWithoutChildItems(): if s.get('close_affected_buffers_when_deleting_even_if_dirty', False): item.closeViews() if s.get('disable_send_to_trash', False): if sublime.platform() == 'windows': self.remove('\\\\?\\'+item.path()); else: self.remove(item.path()); else: send2trash(item.path()) SideBarProject().refresh(); except: should_confirm = s.get('confirm_before_permanently_deleting', True) if not should_confirm or sublime.ok_cancel_dialog('There is no trash bin, permanently delete?', 'Yes, Permanent Deletion'): for item in SideBarSelection(paths).getSelectedItemsWithoutChildItems(): if s.get('close_affected_buffers_when_deleting_even_if_dirty', False): item.closeViews() if sublime.platform() == 'windows': self.remove('\\\\?\\'+item.path()); else: self.remove(item.path()); SideBarProject().refresh(); window_set_status(key, '')
def on_done(self, old, new): if s.get('close_affected_buffers_when_deleting_even_if_dirty', False): item = SideBarItem(new, os.path.isdir(new)) item.closeViews() if sublime.platform() == 'windows': self.remove('\\\\?\\'+new); else: self.remove(new) SideBarProject().refresh();
def open(self, use_powershell = True): if self.isDirectory(): import subprocess if sublime.platform() == 'osx': subprocess.Popen(['/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal', '.'], cwd=self.forCwdSystemPath()) elif sublime.platform() == 'windows': if use_powershell: try: subprocess.Popen(['start', 'powershell'], cwd=self.forCwdSystemPath(), shell=True) except: subprocess.Popen(['start', 'cmd', '.'], cwd=self.forCwdSystemPath(), shell=True) else: subprocess.Popen(['start', 'cmd', '.'], cwd=self.forCwdSystemPath(), shell=True) elif sublime.platform() == 'linux': subprocess.Popen(['gnome-terminal', '.'], cwd=self.forCwdSystemPath()) else: if sublime.platform() == 'osx': import subprocess subprocess.Popen(['open', self.name()], cwd=self.dirname()) elif sublime.platform() == 'windows': import subprocess subprocess.Popen(['start', '', escapeCMDWindows(self.path())], cwd=self.dirname(), shell=True) else: from . import desktop desktop.open(self.path()) print('using desktop')
def _moveMoveViews(self, old, location): for window in sublime.windows(): active_view = window.active_view() views = [] for view in window.views(): if view.file_name(): views.append(view) views.reverse(); for view in views: if old == view.file_name(): active_view = self._moveMoveView(window, view, location, active_view) elif view.file_name().find(old+'\\') == 0: active_view = self._moveMoveView(window, view, view.file_name().replace(old+'\\', location+'\\', 1), active_view) elif view.file_name().find(old+'/') == 0: active_view = self._moveMoveView(window, view, view.file_name().replace(old+'/', location+'/', 1), active_view)
def closeViews(self): path = self.path() closed_items = [] for window in sublime.windows(): active_view = window.active_view() views = [] for view in window.views(): if view.file_name(): views.append(view) views.reverse(); for view in views: if path == view.file_name() or view.file_name().find(path+'\\') == 0 or view.file_name().find(path+'/') == 0: if view.window(): closed_items.append([view.file_name(), view.window(), view.window().get_view_index(view)]) if len(window.views()) == 1: window.new_file() window.focus_view(view) window.run_command('revert') window.run_command('close') # try to repaint try: window.focus_view(active_view) window.focus_view(window.active_view()) except: try: window.focus_view(window.active_view()) except: pass return closed_items
def on_activated_async(self, view): vsettings = view.settings() if (is_markdown_view(view) and get_settings().get(ON_OPEN) and not vsettings.get(PREVIEW_ENABLED) and vsettings.get('syntax') != 'Packages/MarkdownLivePreview/' + \ '.sublime/MarkdownLivePreviewSyntax' + \ '.hidden-tmLanguage' and not any(filter(lambda window: window.settings().get(PREVIEW_WINDOW) is True, sublime.windows()))): sublime.run_command('new_markdown_live_preview')
def run(self, edit): ret = sublime.ok_cancel_dialog('Erase Customized Log Highlight Syntax & Theme ?') if ret: try: wins_l = sublime.windows() for w in wins_l: s_view = w.get_output_panel('loghighlight') if s_view: w.run_command("hide_panel", {"panel": "output.loghighlight"}) s_view.set_syntax_file('Packages/Log Highlight/Log Highlight.tmLanguage') s_view.settings().set('color_scheme', 'Packages/Log Highlight/Log Highlight.hidden-tmTheme') view_l = w.views() for v in view_l: if check_syntax(v): v.set_syntax_file('Packages/Log Highlight/Log Highlight.tmLanguage') v.settings().set('color_scheme', 'Packages/Log Highlight/Log Highlight.hidden-tmTheme') usr_syntax = os.path.join(sublime.packages_path(), 'User/Log Highlight.tmLanguage') if os.path.exists(usr_syntax): os.remove(usr_syntax) usr_theme = os.path.join(sublime.packages_path(), 'User/Log Highlight.hidden-tmTheme') if os.path.exists(usr_theme): os.remove(usr_theme) except Exception: disp_exept() ## Log Highlight ____________________________________________ # to prevent re-run in short time
def unload_all_clients(): for window in sublime.windows(): for client in window_clients(window).values(): unload_client(client)
def check_window_unloaded(): global clients_by_window open_window_ids = list(window.id() for window in sublime.windows()) iterable_clients_by_window = clients_by_window.copy() closed_windows = [] for id, window_clients in iterable_clients_by_window.items(): if id not in open_window_ids: debug("window closed", id) closed_windows.append(id) for closed_window_id in closed_windows: unload_window_clients(closed_window_id)
def get_window_view(vid): """Look for the given vid in all the opened windows """ for window in sublime.windows(): view = get_view(window, vid) if view is not None: return view
def _search_existing_view(self): """ returns True if a view with the name of this ArcticTypescript view is open and sets it as reference """ for w in sublime.windows(): for v in w.views(): if v.name() == self.name: self._view_reference = v self.on_overtook_existing_view() return self._is_view_still_open() return False
def __init__(self, startview): self.processes = None self.compiler = None self.errors = None self.highlighter = None self.tsserver = None self.completion = None if not startview.is_valid() or startview.window() is None: return self.id = random_str() OPENED_PROJECTS[self.id] = self self.project_file_name = startview.window().project_file_name() self.windows = [] # All windows with .ts files self.error_view = {} #key: window.window_id, value: view self.views = [] # All views with .ts files self.tsconfigdir = find_tsconfigdir(startview.file_name()) self.tsconfigfile = os.path.join(self.tsconfigdir, "tsconfig.json") self.is_compiling = False self.authorized_commands = [] self.forbidden_commands = [] self.ArcticTypescript_sublime_settings = sublime.load_settings('ArcticTypescript.sublime-settings') self.open(startview) self._initialize_project() # ############################################### INIT ################
def collect_untracked_views_and_update_content(self, on_finished): """ Searches for opened ts views which belong to this project, add them to this project, transfer the current workspace view content to the tsserver and call on_finished afterwards. """ def _collect_and_update_runner(fileslist): fileslist_normcased = [os.path.normcase(f) for f in fileslist] for w in sublime.windows(): for v in w.views(): if not is_ts(v): continue v_tsconfigdir = find_tsconfigdir(v.file_name()) v_tsconfigfile = os.path.join(v_tsconfigdir, "tsconfig.json") v_tsconfigfile = os.path.normcase(v_tsconfigfile) # belong to same tsconfig AND is already registered in tsconfig[files] # or referenced by other files in tsconfig[files] = fileslist if v_tsconfigfile == os.path.normcase(self.tsconfigfile) \ and os.path.normcase(v.file_name()) in fileslist_normcased: self.open(v) self.tsserver.update(v) on_finished() self.tsserver.get_tss_indexed_files(_collect_and_update_runner) # ############################################### OPEN/CLOSE ##########
def close(self, view): """ Should be called if a view has been closed. Also accepts views which do not belong to this project Closes project if no more windows are open. """ if view in self.views: self.views.remove(view) Debug('project+', "View %s removed from project %s" % (view.file_name(), self.tsconfigfile)) for window in self.windows: # view.window() = None, so iterate all self._remove_window_if_not_needed(window) # ############################################### KILL ################
def _tsserverkilled(self): if self.processes: self.processes.kill() self.views = [] self.windows = [] OPENED_PROJECTS.pop(self.id) if self.on_project_closed: self.on_project_closed()
def get_any_ts_view(): v = sublime.active_window().active_view() if is_ts(v) and not is_dts(v): return v for w in sublime.windows(): for v in w.views(): if is_ts(v) and not is_dts(v): return v
def get_any_view_with_root(root): return from .system.Liste import get_root v = sublime.active_window().active_view() if is_ts(v) and not is_dts(v) and get_root(v.file_name()) == root: return v for w in sublime.windows(): for v in w.views(): if is_ts(v) and not is_dts(v) and get_root(v.file_name()) == root: return v
def find_view(self, img_file_name): for window in sublime.windows(): return window.find_open_file(os.path.abspath(img_file_name)) return None
def search_views_by_title(needle): """ Search for views in all open windows containing the given needle. """ result = [] for window in sublime.windows(): for view in window.views(): name = Utils.get_name_or_file_name_from_view(view) if needle in name: result.append(view) if needle == name: result.append(view) return result
def find_view_by_id(view_id): """ Finds a view in all open windows containing the given id. """ for window in sublime.windows(): for view in window.views(): if view.id() is view_id: return view return None
def close_view(view): """ Closes the given view by running the close_by_index command. If there are more than one open windows and the window has no more views it gets closed, too. """ window = view.window() group_index, view_index = window.get_view_index(view) window.run_command('close_by_index', {'group': group_index, 'index': view_index}) if len(sublime.windows()) > 1 and len(window.views()) is 0: window.run_command('close')