Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VimL: Checking if function exists

Tags:

vim

vim-plugin

right now I'm cleaning up my .vimrc file to make sure it's compatible on most systems.

In my statusline I use a function that another plugin sets, the GitBranchInfoString() function introduced by this plugin.

What I wanna do is check if this function is set, and only then add it to the statusline. It would be in it's own line so I just need to check for it.

What would be the simplest way to accomplish this?

Thanks for all your help!

EDIT:

I have the following:

if exists('*GitBranchInfoString')
    let &stl.='%{GitBranchInfoString()}'
endif
like image 327
greduan Avatar asked Dec 04 '12 19:12

greduan


People also ask

How do you check if a function exists or not?

The code in the brackets will execute if the function is defined. If instead you just test the function without using the window object, for example as if(aFunctionName) , JavaScript will throw a ReferenceErorr if the function doesn't exist.

How do you check if a method exists on an object JavaScript?

Use the typeof operator to check if a method exists in a class, e.g. if (typeof myInstance. myMethod === 'function') {} . The typeof operator returns a string that indicates the type of the specific value and will return function if the method exists in the class.

What is in Vim script?

Vim's scripting language, known as Vimscript, is a typical dynamic imperative language and offers most of the usual language features: variables, expressions, control structures, built-in functions, user-defined functions, first-class strings, high-level data structures (lists and dictionaries), terminal and file I/O, ...


3 Answers

Use

if exists("*GitBranchInfoString")
    " do stuff here
endif
like image 141
ZyX Avatar answered Oct 14 '22 06:10

ZyX


Just as an alternative you may also use a regexp to decide if the plugin at hand is in your runtimepath:

if &rtp =~ 'plugin-name'
    ...
endif

This has the advantage that it works with plugins that only have vimscript code in the autoload directory, which in turn can't be detected when .vimrc is initially parsed since the autoload snippets are loaded at the time of a function call.

like image 30
bergercookie Avatar answered Oct 14 '22 05:10

bergercookie


The currently selected answer doesn't work for me (using Vim 7.4 / Ubuntu). I believe that's because:

.vimrc is sourced before any plugins are loaded

As @ZyX noted this in a comment.

My preferred method is just to check for the existence of the plugin file. I find this cleaner than writing a separate function in an external file.

if !empty(glob("path/to/plugin.vim"))
   echo "File exists."
endif
like image 34
user3751385 Avatar answered Oct 14 '22 06:10

user3751385