TransWikia.com

How to provide shared variables for plugins?

Vi and Vim Asked on February 13, 2021

I’ve written some Vimscript code* in which it’s convenient to have a set of shared color names. To use the names, so far I’ve had to rely on code like this:

execute 'source ' . expand('<sfile>:p:h:h') . '/plugin/colornames.vim'

This means that the scripts have to know something about where the names are defined. Although all of the code is strictly for my own use, I don’t like introducing that kind of dependency.

Is there a general way to define Vimscript constants for use by all the (other) plugins?


* colors/custom.vim, status line plugin, tab line plugin.

2 Answers

Looks like you need a library plugin that other plugins can depend on.

So far the best way to have library plugins is through autoload plugin files. These files are lazily loaded, they are loaded on demand.

EDIT: IOW, the following will be enough

" library plugin: autoload/colorname.vim
let g:colornames#red = 'rouge'


" client plugin
let red = g:colornames#red
Unfortunately, using a variable named after an autoload plugin won't load the plugin. It only works with functions. This means that at best you can replace runtime plugin/colornames.vim " do you really need to tell where the file is defined? I don't think so with call colornames#let_s_explicitly_load_the_plugin_or_any_other_function_name() Note: We may think that `:runtime plugin/whatever.vim` is less convoluted, yet it has a big disadvantage: it is always loaded. An autoload plugin is loaded only when we need it. It may never get loaded. In the past (before vim7), I was using `macros/` directory to store global scripts that I don't always need.

Correct answer by Luc Hermitte on February 13, 2021

Well, such sort of questions tends to be too vague. But here are a couple of thoughts.

  1. If it's solely "for private use", I could even consider modifying $VIMRUNTIME/rgb.txt. Sure, it feels dirty, but if no one else can see it then why the hell is not?

  2. You can simply use global variables, as it's "for private use" only. Declare them in your vimrc and they will be available in all your scripts. Use compound types to minimize global namespace pollution.

  3. If it already starts feeling like a sort of "a huge functions library" then you will come to using "autoload" feature anyway. You can even add a bunch of "autoloaded" getters/setters and finally implement that (useless in 99% of cases) "encapsulation".

  4. If it's just a shared data and it is probably to be edited, I would think of JSON, as VimScript natively supports it. Sure, that will leave the question where to store and find the data file, but for data files it's absolutely normal to have some sort of "../data" subpath fixed.

Answered by Matt on February 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP