zyedidia / micro

A modern and intuitive terminal-based text editor
https://micro-editor.github.io
MIT License
25.15k stars 1.17k forks source link

package.path is missing the path of the plugins directory #1593

Open akowiz opened 4 years ago

akowiz commented 4 years ago

When developing a plugin, it is currently a challenge to write multi-lua file plugin.

Since lua5.1, the recommended way to build a module is the following (in file mod.lua):

local mod = {}

function mod.Foo()
end

function mod.Bar()
end
...
return mod

And in your main script you do:

local m = require("mod")

m.Foo()
m.Bar()

Previously (lua5.0 and early lua5.1), the language provided a mechanism to define a module using a specific statement module("mod", package.seeall) and defining methods in a different way. But this method has been deprecated and it is recommended to use new module style. (see http://lua-users.org/wiki/LuaModuleFunctionCritiqued).

So using the new module style, we can not use PluginAddFile() to load an extra lua file (because it doesn't return a reference to the table from the module). Using the new module style, we are forced to use the require() method to load extra modules. The require method does a search for module along a predefined set of path (package.path). Unfortunately, the plugin folder is not in the package.path, so we can not do m = require(pluginname/module.lua)

If would be great if micro could expose the path of the plugin directory somewhere (in config?) so that we could modify the package.path as necessary, or better if micro could add the plugin path to the package.path before running any of the plugin.

akowiz commented 4 years ago

Quick follow up, here is what I put at the beginning of my plugin lua files for micro:

local nvb_path = os.getenv("HOME") .. '/.config/micro/plug/navbar/'
if not string.find(package.path, nvb_path) then
    package.path = nvb_path .. "?.lua;" .. package.path
end

I am not sure how 'portable' this is, and whether it will work on all platforms (it does work on linux, android w/ termux). If you think this is enough and should be the proper way to develop multi-lua-files plugins, then you can probably close this issue.

akowiz commented 4 years ago

micro does have a ConfigDir variable defined in internal/config/config.go that hold the directory of the current configuration. Unfortunately, I don't know how to retrieve this information while running the plugin. The variable is not exported in cmd/micro/initlua.go

sum01 commented 4 years ago

@akowiz Did you figure out how to access ConfigDir now? My tests all return nil. Is this a bug?