Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim: where to put default values for plugin variables?

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

Ideally, I would like to have those variables set before .vimrc is loaded, such that the user can override these values if he wants to. Is that possible?

like image 441
chtenb Avatar asked Mar 09 '13 09:03

chtenb


3 Answers

Are you writing a plugin?

Your plugin will likely be executed after your user's ~/.vimrc: you can't do anything before that.

You could just forget about doing anything prior to the execution of ~/.vimrc and use conditionals in your script:

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

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

call file_name#function_name()

with that function doing all the initialization stuff.

like image 100
romainl Avatar answered Sep 23 '22 05:09

romainl


Your plugin should only set the default value if the variable does not exist when the plugin is loaded. You can check 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 is set in the vimrc, it will not be redefined by your plugin.

like image 27
Prince Goulash Avatar answered Sep 22 '22 05:09

Prince Goulash


There is also the get() approach, taking advantage that you can access the global scope g: as a Dictionary:

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

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

The advantage is that is shorter if you are using lots of variables with default values in your plugin.

like image 43
RubenLaguna Avatar answered Sep 22 '22 05:09

RubenLaguna