Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on_load method doesn't work as expected

Here is simple test for on_load method.

import sublime_plugin

class OnLoadTest(sublime_plugin.EventListener):
    def on_load(self, view):
        print("Tested")

If I open some file, then close this file (Ctrl-W), and then reopen it (Ctrl-Shift-T), the plugin works fine.

However, if I open some file, then close the editor, and then reopen the editor, the plugin will not be launched. (Despite that the file was successfully reopened, thanks to "hot_exit": true and "remember_open_files": true in my preferences).

Is it some bug or just my lack of skills?

I use ST3, build 3126.

like image 262
john c. j. Avatar asked Jul 10 '26 23:07

john c. j.


1 Answers

Whether this is a bug or a conscious design decision has been debated quite a bit over the years, but is fairly well known.

When restoring from the previous session, all open files are put back to the state they were in, which includes things such as the selected text, unsaved changes, modified settings and so on. Sublime starts up and performs those tasks before or while it's actively loading in plugin code in order to make startup as fast as possible.

If on_load is doing something that you need to be done again while coming back from a restored session, you can detect when your plugin is being loaded by defining a module level plugin_loaded() function, which Sublime will call once everything is loaded. In it you can scan through all of the windows and files and take some action.

An example might 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)
like image 57
OdatNurd Avatar answered Jul 14 '26 00:07

OdatNurd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!