Sublime Forum

Run find_next command after opening a file

#1

I need a simple feature in my new plugin which is : open a specified file and than find the first occurrence of a give text.

eg:
Open a file named “xxx.txt” and then search for text “this is a good app” and scroll the opened view to the matched line.

And here is what I have tried:

class OpenAndFindCommand(sublime_plugin.WindowCommand):
    def run(self):
        self.window.open_file("D:\somefile.txt")
        sublime.active_window().run_command("find_next", {"content":"text_to_find"})

    def is_enabled(self):
        return True

Unfortunately it did not work. The file is opened correctly but the cursor is not moved to the match line of the given text.

Then I tried it in another way : I opened the file “D:\somefile.txt” manually and then commented out the line:

#self.window.open_file("D:\somefile.txt")

and this time it works fine.

Any suggestion will be appreciated, thanks :smile:

0 Likes

#2

open_file is an asynchronous command. You must wait for it to finish loading. Also, I recommend using the API instead of find_next. Something like:

def run(self):
	view = self.window.open_file(file_to_load);
	def do_position():
		if view.is_loading():
			sublime.set_timeout(do_position, 100)
		else:
			r=view.find('text_to_find', 0, sublime.IGNORECASE)
			view.show(r)
	do_position()

This should also include some error checking.

0 Likes