Sublime Forum

How can I automatically close files/tabs in sublime text 2 or 3 from the previous branch on git checkout of new branch?

#1

How can I automatically close files/tabs in sublime text 2 or 3 from the previous branch on git checkout of new branch? I couldn’t find any plugins for this. I have tried sublimegit, git,savvygit plugins. But whenever I change branch or checkout a new branch, the files (tabs) that don’t exist in the new branch remain open and marked unsaved. I find this a little confusing. Any solutions?

0 Likes

#2

I looked into this a bit, and it seems like you could perhaps detect when this happens, but I’m not sure if you can actually do anything about it when you detect it. Or at least, not in a pleasing way. This is probably why no plugins currently handle this, if I had to speculate.

The API docs show that you can use view.file_name () to see if Sublime thinks a file name exists for a view (indicating that it was loaded or previously saved); this reports the file name even if the file is missing.

Using os.path.isfile (view.file_name ()) you can determine if a file exists or not; in combination with a safety check with Git that it knows this file exists in some branch, you could conclusively determine that such a view is one you want to have closed.

There is no documented view.close () method, but such a method actually exists. I don’t know if it’s not documented on purpose or not, though.

Where things go a little pear shaped is that such files are (as you noticed) marked as having unsaved changes, even though their view.is_dirty () methods return False. Thus, when you invoke the close method Sublime prompts you if you want to save your changes or not.

I’m not experienced enough with the API’s to know if there is some way around this or not, so as it stands you could implement a command that would find and close such tabs, but you’d have to manually intercede with was such closure, which is a bit of a drag.

0 Likes

#3

I think you can use view.set_scratch(True) to allow closing of unsaved changes.

EDIT: I tested it briefly and it seems to work.

1 Like

#4

Ahh, thank you! I had not tried that, that totally seems to work. Adding that to my bag of tricks (now I have 1 trick in there. ;))

Based on that, something like this is possible, presuming that you can verify with git that you’re doing this only for files that went away as a result of a checkout (or are willing to assume the consequences if some other file went away ;))

1 Like