Sublime Forum

Listen for the document change after command run

#1

How to remove lifetime event listener and only listen for the modification event on command run?

class exampleCommand(sublime_plugin.TextCommand, sublime_plugin.ViewEventListener):
    def run(self, edit):
         print("Comand ran")
    
     def on_modified(self):
          print("Document chang")
0 Likes

#2
    def on_modified(self):
        if self.alive:
            print("Document chang")
0 Likes

#3

@addons_zz I want the on_modified method to run only when the command runs

0 Likes

#4

For how much time?

0 Likes

#5

until the command is running

0 Likes

#6

What are you trying to do? Could this be a XY problem?

A command cannot keep running, otherwise the Sublime Text interface will hang. See: https://github.com/SublimeTextIssues/Core/issues/1463 Packages are allowed to hang Sublime Text Indefinitely

Unless you put a thread to run on background, but on this case, the run command will almost immediately stop. So, there is not much use only allowing the on_modified event running only for that short period of time. Anyways, this code should do it as you describe literally:

class exampleCommand(sublime_plugin.TextCommand, sublime_plugin.ViewEventListener):
    can_run = False

    def run(self, edit):
        self.can_run = True
        print("Comand ran")
        self.can_run = False
    
    def on_modified(self):
        if self.can_run:
            print("Document chang")

With threading it would be like this:

import threading

class exampleCommand(sublime_plugin.TextCommand, sublime_plugin.ViewEventListener):
    can_run = False

    def run(self, edit):
        threading.Thread(target=self.run_long_command, args=("Command ran",)).start()

    def run_long_command(self, argument):
        self.can_run = True
        print(argument)
        self.can_run = False

    def on_modified(self):
        if self.can_run:
            print("Document change")
0 Likes

#7

@addons_zz Thanks

0 Likes