The weirdness that you’re seeing here is most likely caused by you assigning a new view to self.view
inside the run
method, which is not something that you should be doing. Altering the plugin above to the following fixes the problem:
import sublime
import sublime_plugin
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, edit):
window = sublime.active_window()
view = window.new_file()
view.insert(edit, 0, "Hello, World!")
Generally speaking, in Sublime everything that displays text and allows you to edit it (open files, the input areas in the command palette and console, etc) are all view
s. When you define a TextCommand
class, Sublime creates one instance of it for every view
, and in that instance self.view
represents the view that the command was created for, which allows the run
method to know what view it’s running inside of.
(Similarly there is one instance of every WindowCommand
per window
, and self.window
represents that window).
The edit
object that you get as a parameter to the run
method is your gateway to making modifications to views. It wraps all of the changes made by that command and to what view
. Sublime creates it with code like this (in build 3176, this is at line 1064 in sublime_plugin.py
, which you can find in the installation folder of Sublime):
edit = self.view.begin_edit(edit_token, self.name(), args)
try:
return self.run(edit, **args)
finally:
self.view.end_edit(edit)
What you’re seeing here in your problem is that when begin_edit()
is called, it’s called for the view that you originally invoked the command in. Then when end_edit()
gets called, because you assigned a new view to self.view
, the view that ends the edit is not the same as the one that started it and hilarity ensues, where hilarity is defined as “any one of a number of weird unintended artifacts that the core was not expecting to deal with”.
I looked at the issue the OP referenced above, and it looks like this was a problem that was only affecting Sublime Text 3 and not Sublime Text 2. Un-coincidentally, in version 2 you could call begin_edit()
and end_edit()
yourself in order to get an edit object, but in version 3 that API is hidden and used by Sublime behind the scenes.
I didn’t look at the code of the package in question, but I would guess that it was doing something in version 2 that was either technically incorrect but the core reacted better to it, or it was not properly ported to Sublime Text 3 at the time.