Vim: where to set default values ​​for plugin variables?

What is the best way to set default values ​​for plugin variables?

Ideally, I would like these variables to be set before loading .vimrc so that the user can override these values ​​if he wants. Is it possible?

+4
source share
3 answers

Are you writing a plugin?

Your plugin will most likely be executed after your user ~/.vimrc : you cannot do anything before that.

You can simply forget about doing anything before doing ~/.vimrc and use the conventions in the script:

 if !exists("g:pluginname_optionname") let g:pluginname_optionname = default_value endif 

Or you can use the autoload script ( :h autoload ) and ask your users to put something like the following in ~/.vimrc before any configuration:

 call file_name#function_name() 

with this function that performs all the elements of initialization.

+7
source

Your plugin should only set the default value if the variable does not exist when loading the plugin. You can verify this using the exists() function.

For example, at the top of your plugin script:

 if !exists("g:MyPluginVariable") let g:MyPluginVariable = default_value endif 

Now, if g:MyPluginVariable installed in vimrc, it will not be overridden by your plugin.

+3
source

There is also a get() approach that allows access to the global scope g: like Dictionary :

 let g:pluginname#optionname = get(g:, 'pluginname#optionname', default_value) 

get() queries the g: scope as a Dictionary for the pluginname#optionname and returns default_value if it cannot find the key there. The let statement either reassigns the same value that it had, or default_value .

The advantage is that it is shorter if you use many variables with default values ​​in your plugin.

+2
source

All Articles