Python sublime.windows() Examples

The following are 30 code examples of sublime.windows(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sublime , or try the search function .
Example #1
Source File: ksp_plugin.py    From SublimeKSP with GNU General Public License v3.0 6 votes vote down vote up
def play(self, **kwargs):
        sound_path = os.path.join(self.dir, '{}.wav'.format(kwargs['command']))

        if sublime.platform() == "osx":
            if os.path.isfile(sound_path):
                call(["afplay", "-v", str(1), sound_path])

        if sublime.platform() == "windows":
            if os.path.isfile(sound_path):
                winsound.PlaySound(sound_path, winsound.SND_FILENAME | winsound.SND_ASYNC | winsound.SND_NODEFAULT)

        if sublime.platform() == "linux":
            if os.path.isfile(sound_path):
                call(["aplay", sound_path]) 
Example #2
Source File: color_helper.py    From ColorHelper with MIT License 6 votes vote down vote up
def setup_previews():
    """Setup previews."""

    global ch_preview_thread
    global ch_preview
    global unloading

    unloading = True
    if ch_preview_thread is not None:
        ch_preview_thread.kill()
    for w in sublime.windows():
        for v in w.views():
            v.settings().clear_on_change('color_helper.reload')
            v.settings().erase('color_helper.preview_meta')
            v.erase_phantoms('color_helper')
    unloading = False

    if ch_settings.get('inline_previews', False):
        ch_preview = ChPreview()
        ch_preview_thread = ChPreviewThread()
        ch_preview_thread.start() 
Example #3
Source File: project_manager.py    From ProjectManager with MIT License 6 votes vote down vote up
def subl(*args):
    executable_path = sublime.executable_path()
    if sublime.platform() == 'osx':
        app_path = executable_path[:executable_path.rfind('.app/') + 5]
        executable_path = app_path + 'Contents/SharedSupport/bin/subl'

    subprocess.Popen([executable_path] + list(args))

    def on_activated():
        window = sublime.active_window()
        view = window.active_view()

        if sublime.platform() == 'windows':
            # fix focus on windows
            window.run_command('focus_neighboring_group')
            window.focus_view(view)

        sublime_plugin.on_activated(view.id())
        sublime.set_timeout_async(lambda: sublime_plugin.on_activated_async(view.id()))

    sublime.set_timeout(on_activated, 300) 
Example #4
Source File: color_helper.py    From ColorHelper with MIT License 6 votes vote down vote up
def plugin_unloaded():
    """Kill threads."""

    global unloading
    unloading = True

    if ch_thread is not None:
        ch_thread.kill()
    if ch_file_thread is not None:
        ch_file_thread.kill()
    if ch_preview_thread is not None:
        ch_preview_thread.kill()

    # Clear view events
    ch_settings.clear_on_change('reload')
    for w in sublime.windows():
        for v in w.views():
            v.settings().clear_on_change('color_helper.reload')

    unloading = False 
Example #5
Source File: main.py    From LSP with MIT License 6 votes vote down vote up
def plugin_loaded() -> None:
    load_settings()
    popups.load_css()
    set_debug_logging(settings.log_debug)
    set_exception_logging(True)
    windows.set_diagnostics_ui(DiagnosticsPresenter)
    windows.set_server_panel_factory(ensure_server_panel)
    windows.set_settings_factory(settings)
    load_handlers()
    sublime.status_message("LSP initialized")
    window = sublime.active_window()
    if window:
        windows.lookup(window).start_active_views()
    if int(sublime.version()) > 4000:
        sublime.error_message(
            """The currently installed version of LSP package is not compatible with Sublime Text 4. """
            """Please remove and reinstall this package to receive a version compatible with ST4. """
            """Remember to restart Sublime Text after.""") 
Example #6
Source File: main.py    From LSP with MIT License 6 votes vote down vote up
def plugin_unloaded() -> None:
    # Also needs to handle package being disabled or removed
    # https://github.com/sublimelsp/LSP/issues/375
    unload_settings()
    # TODO: Move to __del__ methods
    for window in sublime.windows():
        unload_sessions(window)  # unloads view state from document sync and diagnostics
        destroy_output_panels(window)  # references and diagnostics panels
        for view in window.views():
            if view.file_name():
                remove_highlights(view)
                remove_color_boxes(view)
                for key in ['error', 'warning', 'info', 'hint', 'diagnostics']:
                    view.erase_regions('lsp_{}'.format(key))
                for key in ['diagnostics', 'clients']:
                    view.erase_status('lsp_{}'.format(key))
                for key in ['language', 'active', 'diagnostic_phantom']:
                    view.settings().erase('lsp_{}'.format(key)) 
Example #7
Source File: common.py    From SublimeOutline with MIT License 6 votes vote down vote up
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 
Example #8
Source File: bootstrapper.py    From SublimeScraps with MIT License 6 votes vote down vote up
def disable_resources(self):
        """
        Disables all resources being provided by the system bootstrap package
        by saving the state of items that are using them and then reverting
        them to temporary defaults.
        """
        prefix = "Packages/{pkg}/".format(pkg=bootstrap_pkg)

        # TODO if the package also contains a custom color scheme, this should
        # also temporarily reset the color scheme back to defaults and then
        # restore them later.
        for window in sublime.windows():
            for view in window.views():
                s = view.settings()
                syntax = s.get("syntax")
                if syntax.startswith(prefix):
                    s.set("_mp_boot_syntax", syntax)
                    s.set("syntax", "Packages/Text/Plain text.tmLanguage") 
Example #9
Source File: GotoWindow.py    From sublime-goto-window with MIT License 6 votes vote down vote up
def on_done(self, selected_index):
        current_index = self._get_current_index()
        if selected_index == -1 or current_index == selected_index:
            return

        folders = self._get_folders()
        window_index = folders[selected_index][1]
        window_to_move_to = sublime.windows()[window_index]

        self.focus(window_to_move_to)

        # OS X and Linux require specific workarounds to activate a window
        # due to this bug:
        # https://github.com/SublimeTextIssues/Core/issues/444
        if sublime.platform() == 'osx':
            self._osx_focus()
        elif sublime.platform() == 'linux':
            self._linux_focus(window_to_move_to) 
Example #10
Source File: focus_editor.py    From Fuse.SublimePlugin with MIT License 6 votes vote down vote up
def tryHandle(self, request):
		if request.name != "FocusEditor":
			return False
		fileName = request.arguments["File"]
		line = request.arguments["Line"]
		column = request.arguments["Column"]
		if not os.path.isfile(fileName):
			self._returnFailure("File '{}' does not exist".format(fileName), request.id)
			return True
		window = self._tryGetWindowFor(request.arguments["Project"])
		if window:
			try:
				window.open_file( "{}:{}:{}".format(fileName, line, column), sublime.ENCODED_POSITION)
				if sublime.platform() == "osx":
					self._focusWindowOSX()
					self.msgManager.sendResponse(self.interop, request.id, "Success")
					return True
				elif sublime.platform() == "windows":
					self.msgManager.sendResponse(self.interop, request.id, "Success", {"FocusHwnd":window.hwnd()})
					return True
			except Exception as e:
				self._returnFailure(str(e), request.id)
				return True
		return False 
Example #11
Source File: temp_directory_test_case.py    From UnitTesting with MIT License 6 votes vote down vote up
def setUpClass(cls):
        """Create a temp directory for testing."""
        cls._temp_dir = tempfile.mkdtemp()
        nwindows = len(sublime.windows())
        original_window_id = sublime.active_window().id()
        sublime.run_command("new_window")

        yield lambda: len(sublime.windows()) > nwindows

        yield lambda: sublime.active_window().id() != original_window_id

        cls.window = sublime.active_window()

        project_data = dict(folders=[dict(follow_symlinks=True, path=cls._temp_dir)])
        cls.window.set_project_data(project_data)

        def condition():
            for d in cls.window.folders():
                # on Windows, `cls._temp_dir` is lowered cased,
                # `os.path.normcase` is needed for comparison.
                if cls._temp_dir == os.path.normcase(d):
                    return True

        yield condition 
Example #12
Source File: util.py    From JavaScriptEnhancements with MIT License 6 votes vote down vote up
def subl(args):
  
  executable_path = sublime_executable_path()
  args = [executable_path] + args
  args_list = list()

  if sublime.platform() == 'windows' :
    for arg in args :
      args_list.append(json.dumps(arg, ensure_ascii=False))
  else :
    for arg in args :
      args_list.append(shlex.quote(arg))
  
  args = " ".join(args_list)

  return subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
Example #13
Source File: common.py    From SublimeFileBrowser with MIT License 6 votes vote down vote up
def is_hidden(self, filename, path, goto=''):
        if not (path or goto):  # special case for ThisPC
            return False
        tests = self.view.settings().get('dired_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 
Example #14
Source File: util.py    From JavaScriptEnhancements with MIT License 6 votes vote down vote up
def is_project_open(project): 

  project_folder_to_find = os.path.dirname(project)

  windows = sublime.windows()

  for window in windows :

    project_file_name = sublime.active_window().project_file_name()

    if project_file_name :
      project_folder = os.path.dirname(project_file_name)

      return True if project_folder == project_folder_to_find else False

    else :
      # try to look at window.folders()
      folders = window.folders()   
      if len(folders) > 0:

        project_folder = folders[0]

        return True if project_folder == project_folder_to_find else False

  return False 
Example #15
Source File: 0_dired_fs_observer.py    From SublimeFileBrowser with MIT License 6 votes vote down vote up
def refresh(views, erase_settings=False):
    '''
    views
        list of integers which are view.id(), can be empty
    erase_settings
        boolean, can be True after change of global setting dired_autorefresh
    '''
    if not views and not erase_settings:
        def is_dired(view): return view.settings() and view.settings().get("dired_path")
    else:
        def is_dired(view): return False

    for w in sublime.windows():
        for v in w.views():
            if v.id() in views or is_dired(v):
                if erase_settings:
                    v.settings().erase('dired_autorefresh')
                v.run_command('dired_refresh') 
Example #16
Source File: util.py    From JavaScriptEnhancements with MIT License 5 votes vote down vote up
def sublime_executable_path():
  executable_path = sublime.executable_path()

  if sublime.platform() == 'osx':
    app_path = executable_path[:executable_path.rfind(".app/") + 5]
    executable_path = app_path + "Contents/SharedSupport/bin/subl"

  elif sublime.platform() == 'windows':
    executable_path = os.path.join(os.path.dirname(executable_path), "subl.exe")

  return executable_path 
Example #17
Source File: util.py    From JavaScriptEnhancements with MIT License 5 votes vote down vote up
def _wrapper_func_stdout(args, func_stdout, args_func_stdout=[], chdir=""):

  env = os.environ.copy()
  env["PATH"] = env["PATH"] + javaScriptEnhancements.get("PATH")
  shell = None if sublime.platform() == 'windows' else '/bin/bash'

  with subprocess.Popen(args, shell=True, executable=shell, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, preexec_fn=os.setsid, cwd=(None if not chdir else chdir)) as p:

    func_stdout(None, p, *args_func_stdout)
    
    thread_output = create_and_start_thread(_wrapper_func_stdout_listen_output, "", (p, func_stdout, args_func_stdout))

    thread_error = create_and_start_thread(_wrapper_func_stdout_listen_error, "", (p, func_stdout, args_func_stdout))

    if thread_output:
      thread_output.join()
      
    if thread_error:
      thread_error.join()

    if p.wait() == 0:
      func_stdout("OUTPUT-SUCCESS", p, *args_func_stdout)
    else :
      func_stdout("OUTPUT-ERROR", p, *args_func_stdout)

    func_stdout("OUTPUT-DONE", p, *args_func_stdout) 
Example #18
Source File: view.py    From Terminus with MIT License 5 votes vote down vote up
def panel_window(view):
    for w in sublime.windows():
        for panel in w.panels():
            v = w.find_output_panel(panel.replace("output.", ""))
            if v and v.id() == view.id():
                return w
    return None 
Example #19
Source File: main.py    From Terminus with MIT License 5 votes vote down vote up
def plugin_unloaded():
    # close all terminals
    for w in sublime.windows():
        w.run_command("terminus_close_all")

    theme_plugin_unloaded()
    settings = sublime.load_settings("Terminus.sublime-settings")
    settings_on_change(settings, "debug", clear=True) 
Example #20
Source File: project_in_statusbar.py    From SublimeScraps with MIT License 5 votes vote down vote up
def plugin_loaded ():
    """
    Ensure that all views in all windows show the associated project at startup.
    """
    # Show project in all views of all windows
    for window in sublime.windows ():
        for view in window.views ():
            show_project (view) 
Example #21
Source File: bootstrapper.py    From SublimeScraps with MIT License 5 votes vote down vote up
def enable_resources(self):
        """
        Enables all resources being provided by the system boostrap package by
        restoring the state that was saved when the resources were disabled.
        """
        for window in sublime.windows():
            for view in window.views():
                s = view.settings()
                old_syntax = s.get("_mp_boot_syntax", None)
                if old_syntax is not None:
                    s.set("syntax", old_syntax)
                    s.erase("_mp_boot_syntax") 
Example #22
Source File: configurations.py    From LSP with MIT License 5 votes vote down vote up
def update(self) -> None:
        for window in sublime.windows():
            if window.id() in self._managers:
                self._managers[window.id()].update() 
Example #23
Source File: SideBar.py    From SideBarTools with MIT License 5 votes vote down vote up
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):])
                    ) 
Example #24
Source File: SideBar.py    From SideBarTools with MIT License 5 votes vote down vote up
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) 
Example #25
Source File: SocketThread.py    From CodeAtlasSublime with Eclipse Public License 1.0 5 votes vote down vote up
def goToPage(self, param):
		print('go to page', param)
		import sublime
		window = sublime.active_window()
		for win in sublime.windows():
			if win.id() == self.windowID:
				window = win
		if window:
			window.open_file('%s:%s:%s'% (param[0], param[1], param[2]+1), sublime.ENCODED_POSITION) 
Example #26
Source File: utils.py    From sublimetext-cfml with MIT License 5 votes vote down vote up
def get_project_list():
    project_list = []
    for window in sublime.windows():
        if window.project_file_name():
            project_tuple = (
                normalize_path(window.project_file_name()),
                window.project_data(),
            )
            project_list.append(project_tuple)
    return project_list 
Example #27
Source File: building.py    From Fuse.SublimePlugin with MIT License 5 votes vote down vote up
def _closeOldOutputViews(self):
		for window in sublime.windows():
			for view in window.views():
				if view.settings().has("is_fuse_output_view"):
				    view.close() 
Example #28
Source File: ksp_plugin.py    From SublimeKSP with GNU General Public License v3.0 5 votes vote down vote up
def find_view_by_filename(cls, filename, base_path=None):
        if filename is None:
            return sublime.active_window().active_view()
        if not os.path.isabs(filename) and base_path:
            filename = os.path.join(base_path, filename)

        for window in sublime.windows():
            for view in window.views():
                if view.file_name() and view.file_name() == filename:
                    return view
        return None 
Example #29
Source File: TerminalView.py    From TerminalView with MIT License 5 votes vote down vote up
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) 
Example #30
Source File: fixpaths.py    From SublimeFileBrowser with MIT License 5 votes vote down vote up
def run(self, edit):
        for w in sublime.windows():
            for v in w.views():
                if v.settings():
                    p = v.settings().get("dired_path")
                    if p and p[~0] != os.sep:
                        v.settings().set("dired_path", p+os.sep)

        jp = sublime.load_settings('dired.sublime-settings').get('dired_jump_points', {})
        if jp:
            fix_jp = dict((n if ST3 else n.decode('utf8'), t if t[~0] == os.sep else t+os.sep) for n, t in jp.items())
            sublime.load_settings('dired.sublime-settings').set('dired_jump_points', fix_jp)
            sublime.save_settings('dired.sublime-settings')

        print('\nFileBrowser:\n\tAll fixed. Thank you for patience!\n')