0

I use Plug as my plugin manager and have this line:

Plug 'MyPlugin', { 'for' : 'c'}

which means it should only load the plugin MyPlugin when a file of the filetype c is opened.

This works fine, but right after that I have a function call: call MyPlugin#doSomething(...) which leads to an error everytime I dont open a file of the filetype c. is there some kind of if statement to check if the plugin MyPlugin has been loaded?

  • 2
    If it is your plugin you can set a global variable when it is loaded (let g:loaded_myplugin = 1) and then check if this variable exists (if exists("g:loaded_myplugin")). This is usually a best practice to use this kind of variable to avoid loading your plugin several times (see :h write-plugin especially the "NOT LOADING" part) – statox Jan 22 '18 at 10:39
  • 1
    In case it's not 100% clear, almost any plugin you install will already set the variable that @statox describes above, so his solution should work for plugins you haven't written yourself, too. – Rich Jan 22 '18 at 10:53
  • 2
    Note however this is true only for plugin scripts, not for ftplugin scripts (where the situation can be quite chaotic), nor for autoload plugin scripts (where it doesn't make any sense). – Luc Hermitte Jan 22 '18 at 12:03
2

In the case of autoload functions, what I usually do is the following

  1. I check whether the function is known
  2. If not I explicitly try-to-source its autoload plugin, with :runtime that takes care of &rtp, and that fails silently.
  3. I check again whether the function is known

IOW:

if ! exists('*MyPlugin#doSomething')
   runtime autoload/MyPlugin.vim
endif
if exists('*MyPlugin#doSomething')
    call MyPlugin#doSomething(args)
endif

Note: that if your plugin is mainly made of ftplugin and of autoloaded scripts, I don't see the point of the { 'for' : 'c'} specification.

2

Rather than have my ~/.vimrc load a plugin ahead of when it would normally be loaded, I usually solve this problem in one of two ways.

  1. Call the function in a ~/.vimrc/after/plugin/MyPlugin.vim file.

    if exists('*MyPlugin#doSomething') call MyPlugin#doSomething(args) endif

  2. Call the function in an autocommand in your ~/.vimrc so that it will be executed after plugins are loaded.

    au VimEnter * if exists('*MyPlugin#doSomething') | call MyPlugin#doSomething(args) | endif
    
  • I am trying to set this up for NERDTree. It seems that my ~/.vim/after/plugin/nerdtree.vim file is run only at startup and not when nerdree is loaded (with Plug 'scrooloose/nerdtree', { 'on': [ 'NERDTree' ] }). Is there a way to run the file only when NERDTree is loaded? – Marcel Oct 3 at 15:58

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.