Home Download Buy Blog Forum Support

Saving session state in a Plugin

Saving session state in a Plugin

Postby xavi- on Tue Jun 18, 2013 6:46 am


What's the best way to save session state in a plugin? I'm currently using a class/static variable. Is that a good idea or am I asking for trouble?

Posts: 4
Joined: Sat Jun 08, 2013 4:53 pm

Re: Saving session state in a Plugin

Postby bizoo on Tue Jun 18, 2013 11:12 am

I think it's OK.

In addition, you can use view.settings() or window.settings() (in ST3 only) to store something persistently (more or less).
Settings are stored in the session file of your project, so as long as you don't close the view (for view.settings()), the settings are available even if you restart ST.
I suppose it's the same for window.settings() except it's global for the project and not only for a specific view.
Posts: 958
Joined: Wed Dec 08, 2010 6:53 am
Location: Switzerland

Re: Saving session state in a Plugin

Postby miped on Thu Jul 11, 2013 6:08 pm

Class or module-level variables are fine for saving state that needs to be persistent across the entire ST session (both in ST2 and ST3).

As bizoo pointed out, you can use view.settings() in both ST2 and ST3 to save view-specific state and ST3 has window specific state using window.settings(). Unfortunately this doesn't exist in ST2.

To get around that, and get window-specific state in ST2 you have two options:

1. Use a class or module-level dictionary indexed by the window id. This goes something like this:
Code: Select all
class SomeCommand(WindowCommand):

    state = {}
    def run(self):
        # set state
        SomeCommand.state.setdefault(self.window.id(), {})['mystate'] = 'myvalue'

        # get state
        SomeCommand.state.get(self.window.id(), {}).get('mystate')

2. If you don't want the class or module-level stuff (i.e. maybe it doesn't fit with your project structure), you can use the sublime settings, like so:
Code: Select all
class SomeOtherCommands(WindowCommand):

    def run(self):
        state = sublime.load_settings('SomeOtherCommandWindowState')  # long and unique name, unlikely to exist

        # set state
        state.setdefault(self.window.id(), {})['mystate'] = 'myvalue'

        # get state
        state.get(self.window.id(), {}).get('mystate')

Any way you slice it, per-window state gets a little dirty in ST2.
SublimeGit: Git integration for Sublime Text 2 and 3
Posts: 16
Joined: Mon Jul 08, 2013 6:30 pm

Return to Plugin Development

Who is online

Users browsing this forum: No registered users and 8 guests