Sublime Forum

Avoiding recursion when running a command from `on_modified`?

#1

I’m writing a plugin that keeps markdown tables aligned while you type. The listener is:

class AlignMarkdownTableListener(sublime_plugin.ViewEventListener):
    @classmethod
    def is_applicable(self, settings):
        return settings.get('syntax').endswith('gfm.sublime-syntax')

    def on_modified(self):
        self.view.run_command('align_markdown_table')

The command align_markdown_table will check whether the table is correctly aligned and call view.erase or view.insert zero or more times. I’m getting a RuntimeError: maximum recursion depth exceeded. Presumably, the command is triggering the listener.

Is there a reasonable way to keep this from happening?

0 Likes

#2

I’m not sure if it’s reasonable or not, but I’ve done this in the past (in the linked SO answer below) by having the event listener keep a list of view ID’s that it’s currently in the process of modifying, and adding/removing the view from the list while the modification is being handled.

[edit]In your case, since you’re using a view event listener and there’s one per view, you can probably just throw an extra field in there to get the same effect with less hassle? [/edit]

Presumably the same could be done by creating a temporary setting in the view whose value you toggle and check as well. I can’t remember off hand why I didn’t go that particular route in this case though.

That also points out that modifications are also triggered when the user performs an undo action, which may also be something you want to guard against.

1 Like