Take the 2-minute tour ×

I'm writing a SublimeText Plugin that uses a shelf for persistent storage of some data; the path of the shelf file is defined in the settings of the current project. I have a WindowCommand and a keybinding for it that initializes the class that holds the shelf, but I want to automatically execute this on startup if a suitable project is open.

Simply running the command when the plugin is loaded fails because sublime.active_window() is still uninitialized - my current workaround is to use set_timeout with a (hopefully) large enough timeout:

import sublime, sublime_plugin

_data = None

class MkshelfCommand(sublime_plugin.WindowCommand):
    def run(self):
        global _data
        shelf_path = self.window.active_view().settings().get("shelf_path")
        if shelf_path:
            _data = MyClass(shelf_path)

sublime.set_timeout(lambda: sublime.active_window().run_command("mkshelf"), 1000)

This is obviously all kinds of bad; but I couldn't figure out how to do this more reliably as I could neither find a way to access the current projects settings without a view, nor a method to ensure the window exists before executing the command so I could get rid of the timeout (I've thought of abusing EventListener.on_activated, but this seems even more ugly than what I'm doing right now). Is there a better way to do this or should I just bite the bullet and stick with my current approach?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Instead of calling sublime.active_window() directly in you timeout callback, call a function that calls itself when active_window() is still None:

def runCommandWhenInitialized():
    activeWindow = sublime.active_window()
    if activeWindow is not None:
        sublime.set_timeout(lambda: runCommandWhenInitialized(), 100)

sublime.set_timeout(lambda: runCommandWhenInitialized(), 100)

(I didn't actually run this code, but I think it should work.)

share|improve this answer
I had hoped for something that would feel less like a hack, but it seems SublimeText doesn't offer anything better do deal with a situation like this (which seems to be normal for half of my use cases, like "close a view"). I chose to accept your solution as it is a reasonably safe refinement of my code and should suffice as a workaround. –  l4mpi Oct 24 '13 at 18:20
I agree, I wish there was a "sublime has finished booting up, restored all windows and loaded all plugins" event. I have needed that in a couple of instances. –  DudeOnRock Oct 24 '13 at 19:03

Your Answer


