The open_file
command (and the window.open_file()
API call) both create a new view on each invocation, as you’ve noticed. I don’t think Sublime has an analog for opening a file into an already existing view out of the box.
As such, if you want to replace the contents of a view that already exists with another file, I believe your plugin would need to manually load the new file content itself, then tell the view to replace it’s contents with the data that you loaded, or close the view and then open a new one.
That said, it looks like your sample code is using the open_file
command as a shortcut for creating a new temporary view and putting some data into it. If that is the case, then you need to track the view after you’ve created it and then just replace it’s contents as needed.
Either way, the following contrived code is an example of tracking and re-using a view. Every time you invoke the example
command, it will either create a new temporary view or re-use the previously created view, and swap the content and title to something new so you can tell it’s working.
As written this always uses whatever the active window is, so if you invoke the command in a window that doesn’t have a temporary view while another window does, you end up with a new one specific to the window. If that’s not what you want, you need to modify the _find_views()
example code to scan all views in all windows instead of all views in the current window.
import sublime
import sublime_plugin
import random
import string
def _find_view(window=None):
"""
Check the current window for our temporary view.
"""
window = sublime.active_window() if window is None else window
for view in window.views():
if view.settings().get("_temp_view", False):
return view
def _temp_view(title, text, window=None, view=None):
"""
Set the tab title and content of the provided view. If no view is provided,
a new one is created first.
"""
window = sublime.active_window() if window is None else window
if view is None:
view = window.new_file()
view.settings().set("_temp_view", True)
else:
view.sel().clear()
view.sel().add(sublime.Region(0, view.size()))
view.run_command("left_delete")
view.set_name(title)
view.run_command("append", {"characters": text})
class ExampleCommand(sublime_plugin.ApplicationCommand):
"""
Contrived example of creating or re-using a view.
"""
count = 0
def run(self):
self.count += 1
msg = "".join([random.choice(string.ascii_letters) for i in range(32)])
_temp_view("Untitled %d" % self.count, "Text: %s" % msg,
view=_find_view())