Sublime Forum

View object returned by window.open_file(...) [solved]

#1

In my plugin, I’m attempting to open a file in the current project as follows:

class NotWorkingCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view.window().open_file(os.path.join(os.path.cwd(), "test.txt"))
        print view.size()

The file opens correctly, however view.size() returns 0 for this returned view object, as does sublime.active_window().active_view().size(). Any idea what could be going wrong?

Edit - If the file is already open, then it works as expected. So it looks like size() is zero because the view object is still being initialize (or something like that). Could someone please point me towards how I could add a callback or listener that would be triggered once the view has fully loaded? I don’t think I can use on_load as-is, because I need to jump to a particular line after loading the file, and that would have to be passed as an argument to the callback.

Edit 2 - view.is_loading()

0 Likes

#2

File loading is asynchronous to make the editor more responsive. What you want to do is something like:

targetView = None

def doStuff(view):
    print view.size()

class LoadListener(sublime_plugin.EventListener):
    def on_load(self, view):
        if view == targetView:
            doStuff(view)
            targetView = None

class NotWorkingCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view.window().open_file(os.path.join(os.path.cwd(), "test.txt"))
        if not view.is_loading():
            doStuff(view)
        else:
            targetView = view
0 Likes

#3

BTW, if you want to jump to a specific line, column you can do

window.open_file("%s:%d:%d" (filename, line, column), sublime.ENCODED_POSITION)
1 Like