Sublime Forum

Refocusing Sublime Text Window


Hi all, I’m having some trouble trying to refocus the Sublime Text window from within a plugin. Note, I’m doing this on macOS, which might be all of the problem!

The context is that I’m using a plugin to call out to a local web API, which in turn activates a GUI that retains window focus after the task is completed. This is the Zotero Better Bibtex CAYW API for those that are curious.

Generally, my query is, what would be the best way to do this?

Specifically, I’m having some trouble with my first attempt, which was to run a subprocess to call the macOS osascript utility, which is just a way to run code in Apple’s AppleScript language intended for automation and whatnot.

For example, on the command line in macOS: osascript -e 'activate application "Sublime Text"' will bring Sublime into focus nicely.

Running this through python’s subprocess module (with subprocess.check_output() for instance) works just fine too. But from within Sublime’s plugin runtime or the console, Sublime hangs for about 30 seconds and then returns an error from check_output().

Any thoughts on what might be going on here?

Sublime Version: 4120



subprocess.check_output() blocks the thread it’s on until it’s complete, but if you’re calling it from a command that means that ST is waiting for that command to complete and thus can’t respond to being activated. Effectively you’ve created a deadlock. I’d suggest either not waiting for the process to complete or doing so in a background thread.

1 Like


Yes … thank you!

Instead of using asyncio I used the sublime module’s apparently generic async “run” function: set_timeout_async() (simple example below).

Otherwise, I should have thought of this at the time … but I think I had gained the false impression that the plugin runtime is a separate thread.

For example (note, macOS specific, I don’t know what the best approach would be for other OS’s)

	def refocus_sublime():  #type: ignore
		# print('refocus!')
		output = subprocess.check_output([
				"osascript", "-e",
				'activate application "Sublime Text"'],
		return output

class MyReFocusCommand(sublime_plugin.TextCommand):

	def run(self, edit):

		...  # lose focus of sublime