On_load method does not work as expected
Here's a simple test for the method on_load
.
import sublime_plugin
class OnLoadTest(sublime_plugin.EventListener):
def on_load(self, view):
print("Tested")
If I open any file, close that file (Ctrl-W) and then open it again (Ctrl-Shift-T), the plugin works great.
However, if I open some file, close the editor and then reopen the editor, the plugin won't run. (Even though the file was opened successfully, thanks "hot_exit": true
also "remember_open_files": true
to my settings).
Is this some mistake or just a lack of skill?
I am using ST3, build 3126.
source to share
Whether this is a mistake or a deliberate design decision has been debated quite a bit over the years but is pretty well known.
When restoring from a previous session, all open files are reverted to the state they were in, including things like selected text, unsaved changes, changed settings, etc. Sublime launches and runs these tasks before or while actively loading into the plugin code to make it launch as quickly as possible.
If on_load
it does something that you need to do again, returning from the restored session, you can detect when your plugin is loading by defining a level plugin_loaded()
- level function that Sublime will call once loaded. In it you can scan all windows and files and take some action.
An example could be:
import sublime
import sublime_plugin
import os
def plugin_loaded ():
# Show project in all views of all windows
for window in sublime.windows ():
for view in window.views ():
show_project (view)
def show_project(view):
# Sometimes a view is not associated with a window
if view.window() is None:
return
# Is there a project file defined?
project_file = view.window ().project_file_name ()
if project_file is not None:
# Get the project filename without path or extension
project_name = os.path.splitext (os.path.basename (project_file))[0]
view.set_status ("00ProjectName", "[" + project_name + "]")
# Display the current project name in the status bar
class ProjectInStatusbar(sublime_plugin.EventListener):
# When you create a new empty file
def on_new(self, view):
show_project (view)
# When you load an existing file
def on_load(self, view):
show_project (view)
# When you use File > New view into file on an existing file
def on_clone(self, view):
show_project (view)
source to share