Sublime Forum

Saving session state in a Plugin

#1

Hello,

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?

Thanks,
Xavi

0 Likes

#2

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.

0 Likes

#3

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]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')[/code]

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]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')[/code]

Any way you slice it, per-window state gets a little dirty in ST2.

0 Likes