Sublime Forum

How to wait for open_file()?

#1

Hello, could some tell me how to properly wait for open_file() to finish. I want to perform some operations on newly opened editor.

editor = self.view.window().open_file(f['filename'])
# how to wait for open_file to finish?
start_pos = editor.text_point(f['line_num'], f['char_num'], clamp_column=True)
text_pos = sublime.Region(start_pos, start_pos + f['length'])
editor.show(text_pos)
editor.sel().add(text_pos)
0 Likes

#2

You can use the View.is_loading method to find out when the view has finished loading and then perform any view related operation. In the case, you editor variable will be the view.

0 Likes

#3

Waiting with:

while editor.is_loading():
    time.sleep(5)

is freezing entire program after that i must kill it.

There must be a better option.

0 Likes

#4

Why are you using time.sleep ? That will definitely freeze the main UI thread.

0 Likes

#5

And how I should do it without sleep()?
open_file() has no callback for executing code after file was loaded.

0 Likes

#6

You would do one of two things:

  1. Implement an EventListener or ViewEventListener and listen for the on_load() event; when the event is raised, the file is loaded, and then you do what you want.
  2. Poll in a non-blocking manner

The first one is the recommended way, but it requires you to structure your code in a way that allows you to know, when an on_load event is raised, that it’s a file that you need to do something with.

For a more traditional route:

def do_something_with_loaded_file(view):
    if view.is_loading():
        sublime.set_timeout(lambda: do_something_with_loaded_file(view), 250)
        return

    print('The file has loaded and now I am doing things with it


view = window.open_file('some_filename.txt')
do_something_with_loaded_file(view)

Now the function do_something_with_loaded_file() will either schedule itself to be called again in a short while if the file is not loaded OR do something if it has; it will keep calling itself until eventually the file loads.

That said to do this you need to have some extra function that can take the action, and if you can do that you can probably use an on_load event too.

2 Likes

Bug or Curious Error? (Or newbie mistake?) Message_Dialog focus on newly opened tab