0

I'm trying to write a Sublime Plugin which consists of a TextCommand and an on_modified EventListener. When the command is run, it needs to create a new instance of an object which is associated with the view that the TextCommand was run in. Whenever the on_modifed is called in the EventListener, it needs to use the instance of that class that was produced when the command was last run in the view.

Here's what I tried:

from code import InteractiveConsole

class LivePythonCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        if hasattr(self.view, 'livePythonInterpreter'):
            print('Already had an interpreter, but replacing it.')
        else:
            print("Didn't have an interpreter, making one now.")
        self.view.livePythonInterpreter = InteractiveConsole()

class LivePythonListener(sublime_plugin.EventListener):
    def on_modified(self, view):
        if hasattr(self.view, 'livePythonInterpreter'):
            print('Modified and interpreting.')
        else:
            print('Modified but not interpreting.')

The first time I run the command, I get this message:

Didn't have an interpreter, making one now.

If I modify the buffer, it tells me:

Modified but not interpreting.

I run the command again and it says:

Already had an interpreter, but replacing it.

I modify the buffer again, and it tells me:

Modified but not interpreting.

So LivePythonCommand is able to see the interpreter that it assigns to the view from run to run. And LivePythonListener is listening, but it never sees the livePythonInterpreter that was assigned to view in LivePythonCommand. What am I doing wrong?

ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193

1 Answers1

1

I found a workaround... I'm not sure I like this solution or not, but here it is:

from code import InteractiveConsole

livePythonInterpreters= {}

class LivePythonCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        ic = InteractiveConsole()
        global livePythonInterpreters
        livePythonInterpreters[self.view.buffer_id()] = ic

class LivePythonListener(sublime_plugin.EventListener):
    def on_modified(self, view):
        ic = livePythonInterpreters[view.buffer_id()]

I think it's pretty obvious how this works... I just don't like it on account of needing a global variable. I'd love it if anyone else has a solution that works without a global variable.

ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193