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?
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.
The if exists(...)
is indeed the canonical configuration idiom and the way to go. Of course, you can do a little meta-programming to reduce the duplication (something like function! s:SetDefault( varname, default )
); some plugins do that.
It's good that you intend to allow a great level of customization, on the other hand, unless your plugin deals with a very complex issue (in a text editor?!), 16 config variables is indeed at the high end. You have to consider the effort of documenting all those and testing the various combinations; maybe it's better to start with a simpler reduced approach first and evolve based on user feedback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With