Sublime Forum

View.run_command('save') not working in TextCommand plugin

#1

I have created within the class AutoCompleteAiCommand(sublime_plugin.TextCommand): a function that includes running command save. But it doesn’t do anything, and tried also closing sublime text and re-opening.

class AutoCompleteAiCommand(sublime_plugin.TextCommand):
	def run(self, edit, action):
		view = self.view
		text = 'echo 123;'
		region = view.sel()[0]
		current_line_region = view.line(region)
		view.insert(edit, region.begin(), text)
		view.replace(edit, current_line_region, ' ')
		view.run_command('save')
0 Likes

#3

Your code example is not correct out of the box because the indentation is wrong for the contents of the run() method.

That aside, what do you mean by “it doesn’t do anything”?

In particular, the check that’s done to see if a file is dirty or not is done after the command that did the change is finished executing. So, if you modify the content of a file inside of a TextCommand and then also save the file from inside of the same command, the file will get saved, then your text command finishes executing, it knows that it wrote something into the buffer, and marks the file as dirty.

So, If that’s the case for you, the fix is to not save while the text command is actually running. You can do that by changing the last line of your sample code to:

        sublime.set_timeout(lambda: view.run_command('save'))

This schedules the command to run the save to happen as soon as possible after the current command finishes executing, which lets Sublime finish this command, run the save, and then know that it’s saved.

If this is NOT the case for you, then I would try to replicate this in Safe Mode and see if it behaves differently there.

2 Likes

#4

Working fine, re-indented. Really appreciated it.

1 Like