Sublime Forum

ST3: inserting into new view from set_timeout_async callback

#1

Hi all,

I’m trying to use set_timeout_async to run potentially time consuming code which ultimately inserts into a new scratch view. Something like…

class Something(sublime_plugin.TextCommand):
    def run(self, edit):
        self.edit = edit
        sublime.set_timeout_async(self.doit, 100)

    def doit(self, *args, **kargs):
        ## LONG RUNNING CODE HERE
        n = self.view.window().new_file()
        n.set_scratch(True)
        n.insert(self.edit, 0, u'asdasd')

The new view is created, but the content (‘asdasd’) is not inserted. No error is logged. Is it not possible to insert into a view from a function called by set_timeout_async?

0 Likes

#2

This is due to the change in the api. The edit object expires and isn’t valid in the callback. A workaround should be something like this:

import sublime
import sublime_plugin

class TestCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        sublime.set_timeout_async(lambda: self.view.run_command("sub"), 100)

class SubCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        n = sublime.active_window().new_file()
        n.set_scratch(True)
        n.insert(edit, 0, 'In here')

This is from the porting guide: sublimetext.com/docs/3/porting_guide.html (“Restricted begin_edit() and end_edit()”). The new api allows a new instance of edit object only by making a new TextCommand (as opposed to using view.begin_edit() before).
Hope this helps.

Regards,
Gaurav

0 Likes

#3

Thanks Gaurav. It’s a shame we’re already talking of ‘workarounds’.
I never came across the issue of ‘dangling edits’ that the change aims to solve; It seems a disappointing change to the api.

0 Likes