Sublime Forum

Closing view automatically

#1

I’m terrible when it comes to tab management, just as much in Sublime as I am in Chrome. One of the plugins (Gitsavvy) I use creates these sort of ephemeral tabs showing diffs etc that I accidentally leave open but frequently end up back on accidentally trying to edit code, so I’m trying to automatically close them.

I came up with something like this, however it’s putting Sublime into a really weird state. So if I select a different open file tab, then it’ll close the one I want, however the newly selected file now has the old tab’s name as if somethings got out of sync. Trying to do more tab switching then eventually crashes Sublime.

Is there anything obviously wrong here / something I should know about tab closing?

import sublime
import sublime_plugin

class CloseSpecialTabsOnSwitchCommand(sublime_plugin.EventListener):
    def on_deactivated(self, view):
        if not view.is_valid():
            return
        
        self.close_special_tabs(view)

    def close_special_tabs(self, view):
        # Get the file name of the current view
        file_name = view.file_name()

        # If the file name is None (unsaved file), use the view name (typically the title shown in the tab)
        if not file_name:
            file_name = view.name()

        # Define the prefixes that should trigger closing
        special_prefixes = ["INLINE:", "BRANCHES:", "STATUS:", "REBASE:"]

        # Check if the tab name starts with any of the special prefixes
        if file_name and any(file_name.startswith(prefix) for prefix in special_prefixes):
            if view.is_valid() and view.window():
                # Close the tab if the name matches
                print("closing", file_name)
                view.window().run_command("close_file")
0 Likes

#2

I use this:

import pathlib

def is_relative_to(a, b):
    try:
        pathlib.Path(a).relative_to(b)
        return True
    except (ValueError, TypeError):
        return False

def is_foreign_view(view):
    # some Git view or an empty tab
    if not view.file_name():
        return True
    # a file outside of this project
    for folder in view.window().folders():
        if not is_relative_to(view.file_name(), folder):
            return True
    return False
0 Likes

#3

I think a possible problem you may have is this:

view.window().run_command("close_file")

This will close the tab/view that currently has the focus. Instead you should do:

view.close()
2 Likes

#4

Thanks @giampaolo that could well explain the weird behaviour I’ve seen. I’ll give that a try.

1 Like

#5

Didn’t take long to test, works a charm! Thank you

1 Like