1

I noticed that most of the plugins I use have a line at the start that checks if the plugin has already been loaded. It often looks similar to this:

if exists("g:loaded_commentary")
    finish
endif
let g:loaded_commentary = 1

Why do plugins have to do this? What bad things can happen if I create a plugin and don't add that "exists" guard at the start?

1

It's mainly a pre-plugin manager era thing that permits to prevent a plugin file from being loaded. For people that still install those files directly into ~/.vim/plugin, it still makes sense.

It could still make sense if you distribute a plugin (in the new sense:) made of several files that defines different things. But honestly, it'd be simpler in that case to have options that permits to fine tune what shall always be defined and/or how.

Note: it can also be used to check whether a plugin has been loaded (there exist other methods though), or to obtain the plugin version if we use that variable to store a version id instead of a boolean.

EDIT: Vim help describes another use case that makes a lot of sense (:h write-plugin)

Or the system administrator has dropped it in the system-wide plugin directory, but a user has his own plugin he wants to use. Then the user must have a chance to disable loading this specific plugin.

| improve this answer | |
  • Thanks. That link to the documentation was exactly what I was looking for as well. – hugomg Jun 22 at 0:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.