Sublime Forum

Adding text to a view from input_panel callback

#1

If I try something like this:

class FooCommand(sublime_plugin.TextCommand):

    def run(self, edit, **kwargs):
        self.edit = edit
        window = self.view.window()
        window.show_input_panel(
            "Foo:",
            "",
            self.on_done,
            None,
            None
        )

    def on_done(self, text):
        selection = self.view.sel()
        for region in selection:
            try:
                self.view.replace(
                    self.edit,
                    region,
                    text
                )
            except Exception as e:
                print("Captured error: {}".format(e))

I’ll get the next error Captured error: Edit objects may not be used after the TextCommand's run method has returned, so my question is, how can i add text on the view’s selections (cursors) on the input_panel on_done callback?

Thanks in advance!

0 Likes

#2

The edit object can’t be reused once run() terminates because Sublime uses it internally to group edits together in the undo buffer.

In the general case you need to have another TextCommand that can take the text that you want to manipulate the view with and invoke it. You could rewrite your command so that if it gets text it uses it, otherwise it prompts for text and then invokes itself again. In more complicated cases you may need to create another command to do the work for you.

In this case, the insert command already replaces all selected text at all cursors with the text you provide, so your example could be rewritten as:

class FooCommand(sublime_plugin.TextCommand):
    def run(self, edit, **kwargs):
        window = self.view.window()
        window.show_input_panel(
            "Foo:",
            "",
            lambda text: self.view.run_command("insert", {"characters": text}),
            None,
            None
        )
1 Like

#3

As usual, a lifesaver!!! It works like a charms. Thx a bunch :smiley:

0 Likes