Sublime Forum

[Solved][Question] How to stop (break, kill, return) plugin function if user run Sublime Text command?

#1

1. Briefly

I don’t find, what should I do, that function from Sublime Text plugin will stop, if user run Sublime Text command.

2. Settings

For example, I want to edit @keith-hall countdown timer:

import sublime
import sublime_plugin


class LovernaStandardCommand(sublime_plugin.TextCommand):

    def run(self, edit, seconds=10):
        self.print_seconds(sublime.active_window().new_file(), seconds)

    def print_seconds(self, view, seconds):
        mpg_command = ["mpg123", "-q", "beep-09.mp3"]
        text = ''
        if seconds > 0:
            text = str(seconds)
            if seconds == 5:
                subprocess.Popen(mpg_command, shell=True)
                text += ' seconds'
            sublime.set_timeout_async(
                lambda: self.print_seconds(
                    view, seconds - 1), 1000)
        else:
            text = 'Time over!'
        view.run_command(
            'append', {
                'characters': text + '\n', 'scroll_to_end': True})

3. Steps to reproduce

User run loverna_standard command → user run force_quit command.

4. Expected behavior

loverna_standard command will stop.

5. Did not help

  1. I add:
import sys


class KeyBindingListener(sublime_plugin.EventListener):

    def on_window_command(self, window, name, args):
        if name == 'force_quit':
            print("Run Force Quit")
            # Stop function
            # http://stackoverflow.com/a/73673/5951529
            sys.exit()

It doesn’t work, I still hear sound from print_seconds function (used mpg123 player).

2. I use raise SystemExit and return instead of sys.exit().
3. I use try... except

def run(self, edit, seconds=10):
    try:
        self.print_seconds(sublime.active_window().new_file(), seconds)
    except self.view.run_command('force_quit'):
        print("Run force_quit command!")
        return

Thanks.

0 Likes

#2

there is no way to cancel a timeout in ST, only ignore the callback when it is fired.
maybe add

if not view.is_valid():
    return

to the top of the print_seconds method

1 Like

#3

Thanks, it works for me! I can not even find documentation is_valid() method.

(Offtop): @kingkeith, I can slightly change your plugin, add documentation and push it to GitHub? If yes, what license do you allow to use your plugin?

Thanks.

1 Like

#4

yes, feel free - as I posted on SO it automatically gets a MIT license, but the full header isn’t necessary, just a link to SO will suffice :slight_smile:

sometimes the only way to find stuff is by exploring and experimenting e.g. dir(view) or searching the forums to see if anyone else has done something similar :slight_smile:

2 Likes