Comment.nvim
Comment.nvim copied to clipboard
`setmetatable` based Lua API
Problem
Currently every Lua API is a function call, which is fine, but most of them are similar to others only having different arguments and uses same call under the hood. This is not extensible if we want to create a new mode #17 and have slight maintenance burden.
Solution
Using setmetatable
we can probably build-up the API as we go. This will be extensible and have less maintenance overhead. By using metatable, the API will look something like this.
All API functions are dot repeatable except
*.count()
require('Comment.api').toggle.linewise()
require('Comment.api').toggle.linewise.current()
require('Comment.api').toggle.linewise.count()
require('Comment.api').toggle.blockwise()
require('Comment.api').toggle.blockwise.current()
require('Comment.api').toggle.blockwise.count()
require('Comment.api').comment.linewise()
require('Comment.api').comment.linewise.current()
require('Comment.api').comment.linewise.count()
require('Comment.api').comment.blockwise()
require('Comment.api').comment.blockwise.current()
require('Comment.api').comment.blockwise.count()
require('Comment.api').uncomment.linewise()
require('Comment.api').uncomment.linewise.current()
require('Comment.api').uncomment.linewise.count()
require('Comment.api').uncomment.blockwise()
require('Comment.api').uncomment.blockwise.current()
require('Comment.api').uncomment.blockwise.count()
Prototype
local U = require('Comment.utils')
local Op = require('Comment.opfunc')
local Config = require('Comment.config')
local t = {
linewise = U.ctype.line,
blockwise = U.ctype.block,
}
local function actions(this, ctype)
return setmetatable({ cmode = this.cmode, ctype = ctype }, {
__index = {
current = function(opmode, cfg)
Op.opfunc(opmode, cfg or Config:get(), this.cmode, t[ctype], U.cmotion.line)
end,
count = function(count, cfg)
Op.count(Config.count or count, cfg or Config:get(), t[ctype])
end,
},
__call = function(that, opmode, cfg)
Op.opfunc(opmode, cfg or Config:get(), that.cmode, t[that.ctype], U.cmotion._)
end,
})
end
return {
toggle = setmetatable({ cmode = U.cmode.toggle }, { __index = actions }),
comment = setmetatable({ cmode = U.cmode.comment }, { __index = actions }),
uncomment = setmetatable({ cmode = U.cmode.comment }, { __index = actions }),
}