6

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?

chtenb
  • 14,924
  • 14
  • 78
  • 116

3 Answers3

10

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.

romainl
  • 186,200
  • 21
  • 280
  • 313
3

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.

Prince Goulash
  • 15,295
  • 2
  • 46
  • 47
2

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.

RubenLaguna
  • 21,435
  • 13
  • 113
  • 151