Prism - Hooks list

I started my first Prism plugin. Prism uses hooks or in other software often called events to get simple plugin architecture. It is often a good idea to get an overview about all available hooks that Prism runs without any plugins. I will show in this post a small list with some explainations.

Prism hooks

Hooks are in Prism the same as in other software, some call hooks also events. Prism runs the hooks and our plugin has the possibility to add a callback on a hook.

Run a hook

Here a small run example with the very popular hook complete.

_.hooks.run('complete', env);

The underscore _ variable is in this case Prism itself and the env variable looks something like that.

var env = {
    element: element,
    language: language,
    grammar: grammar,
    code: code
};

The env variable will be injected into our callback function if we add on a hook.

Add a hook

Here a small example of a minimal plugin that adds a callback on the hook complete.

(function(){
if (typeof self === 'undefined' || !self.Prism || !self.document || !document.querySelector) {
	return;
}
Prism.hooks.add('complete', function(env) {
    console.log("Hello Prism");
});
})();

Creating a Prism hook list

As mentioned above it can be very helpful to get an overview about all hooks that are availabe. I often put just a console.log into the hooks.run function of prism.js and refresh the browser window.

hooks: {
    all: {},

    add: function (name, callback) {
        var hooks = _.hooks.all;

        hooks[name] = hooks[name] || [];

        hooks[name].push(callback);
    },

    run: function (name, env) {
        console.log(name);
        var callbacks = _.hooks.all[name];

        if (!callbacks || !callbacks.length) {
            return;
        }

        for (var i=0, callback; callback = callbacks[i++];) {
            callback(env);
        }
    }
}

Default list of Prism hooks

Here the default list of Prism hooks with the object variables of the env variable.

nameenv
before-highlightallcallback, selector
before-sanity-checkelement, language, grammar, code
before-highlightelement, language, grammar, code
wraptype, content ,tag, classes, attributes, language, parent
before-insertelement, language, grammar, code, highlightedCode
after-highlightelement, language, grammar, code, highlightedCode
completeelement, language, grammar, code, highlightedCode
Next Previous