6

In Vimscript, the script scope s: can be used to avoid name clashes between plugins. I'm writing a Vim plugin in Lua, and I noticed Vim runs all of its Lua code in a common scope. This means my plugin's Lua functions are visible to any other plugin using Lua, and seems like a name clash waiting to happen.

Although my example involves Lua, this question also applies when developing Vim plugins in Python or Ruby. I could just prefix all of my Lua functions with the plugin name, but is there more a reliable/standard way to encapsulate Vim plugin code when using these languages?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Nick Ulle
  • 409
  • 5
  • 14
  • I do not know anythig about vib but if your plugin is separate lua chunk then you can just use local function/variable or use separate environment. – moteus Mar 28 '14 at 09:36
  • That's a better solution than prefixing the plugin name, at least. – Nick Ulle Mar 28 '14 at 17:08
  • [`SirVer/ultisnips`](https://github.com/SirVer/ultisnips.git) may illustrate how to use python in vim plugin development. In particular, refer to the code structure under `pythonx` directory. – Kevin Aug 22 '23 at 03:11

1 Answers1

1

I don't have much experience with lua, but for python things are also similar, especially if you use 'pyfile' (luafile is probably very similar). The better, recommended approach, especially for python would look something like this :

if !exists('g:audiobox_py_loaded')
  python import sys, vim
  python if vim.eval('expand("<sfile>:p:h")') not in sys.path:
        \  sys.path.append(vim.eval('expand("<sfile>:p:h")'))
  python import audiobox
endif

This way, even if you have top level functions in the file audiobox.py, they will get namespaced in a way to 'audiobox' and hence can now be accessed via audiobox. I am sure similiar idioms should be available for lua as well.

For my plugin AudioBox, which I built in my spare time only to learn how I might be able to interface using python, I took that to the next level and wrapped my needed functionality into a class and exposed an object of the same through a setup() method. You can have a look at the code to get a better idea.

NOTE: I am not a python expert by any means so don't judge my code, this was more of a hobby project :).

Dhruva Sagar
  • 7,089
  • 1
  • 25
  • 34
  • You don't have to manually insert the module into `sys.path`. Just put it under `$RTP/pythonx` directory. See `:h pythonx` for detail. – Kevin Aug 22 '23 at 03:06