Elegant way to check if a global plugin variable is set in a vim plugin

Saucier picture Saucier · Apr 7, 2013 · Viewed 13.3k times · Source

I used to use vim during the last years for editing configs and scripts on remote servers. A couple of weeks ago I decided to take the next step and try to use (Mac)vim as my regular editor besides Sublime Text 2. Now I reached a point where I would like to create my first plugin.

My plugin will define ~16 global variables which could be assigned by an user in order to adjust certain properties of the plugin. I asked myself what would be the most elegant way (might be subjective) to check if an user has already assigned his own value to a certain variable. I inspected various other plugins and the "pattern" I see so far seems to be always:

if !exists("g:pluginname_setting")
    let g:pluginname_setting="default"
endif

That seems to be easy and straight forward. But I would always repeat the same piece of code over and over again. Since vi(m) exists for a pretty long time I'm pretty sure people have tried a lot of ways to write plugins and there has been developed some kind of "best practice", which I assume is the "pattern" I gave above as an example. Nevertheless wouldn't it be more elegant to call a function to populate a dictionary which contains all plugin settings and then iterate over the dictionary in order to check the keys to see if an user has already defined his personal preferences? Would that be a good idea or should I rather just drop the idea and stick to the ìf !exists() approach?

Answer

Jérôme picture Jérôme · Nov 18, 2015

There is an elegant way:

let g:pluginname_setting = get(g:, 'pluginname_setting', "default")

I am surprised this is not widely used in plugin settings.