lua: Add vim.opt and fix scopes of vim.o (#13479)

* lua: Add vim.opt

* fixup: cleaning

* fixup: comments

* ty clason

* fixup: comments

* this is the last commit. period.
This commit is contained in:
TJ DeVries 2021-05-28 08:24:48 -07:00 committed by GitHub
parent 192ea01edd
commit 43956dea55
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 1354 additions and 178 deletions

View File

@ -913,8 +913,166 @@ vim.env *vim.env*
<
*lua-vim-options*
From Lua you can work with editor |options| by reading and setting items in
these Lua tables:
*lua-vim-opt*
*lua-vim-set*
*lua-vim-optlocal*
*lua-vim-setlocal*
In vimL, there is a succint and simple way to set options. For more
information, see |set-option|. In Lua, the corresponding method is `vim.opt`.
`vim.opt` provides several conveniences for setting and controlling options
from within Lua.
Examples: ~
To set a boolean toggle:
In vimL:
`set number`
In Lua:
`vim.opt.number = true`
To set an array of values:
In vimL:
`set wildignore=*.o,*.a,__pycache__`
In Lua, there are two ways you can do this now. One is very similar to
the vimL way:
`vim.opt.wildignore = '*.o,*.a,__pycache__'`
However, vim.opt also supports a more elegent way of setting
list-style options, but using lua tables:
`vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }`
To replicate the behavior of |:set+=|, use: >
-- vim.opt supports appending options via the "+" operator
vim.opt.wildignore = vim.opt.wildignore + { "*.pyc", "node_modules" }
-- or using the `:append(...)` method
vim.opt.wildignore:append { "*.pyc", "node_modules" }
<
To replicate the behavior of |:set^=|, use: >
-- vim.opt supports prepending options via the "^" operator
vim.opt.wildignore = vim.opt.wildignore ^ { "new_first_value" }
-- or using the `:prepend(...)` method
vim.opt.wildignore:prepend { "new_first_value" }
<
To replicate the behavior of |:set-=|, use: >
-- vim.opt supports removing options via the "-" operator
vim.opt.wildignore = vim.opt.wildignore - { "node_modules" }
-- or using the `:remove(...)` method
vim.opt.wildignore:remove { "node_modules" }
<
To set a map of values:
In vimL:
`set listchars=space:_,tab:>~`
In Lua:
`vim.opt.listchars = { space = '_', tab = '>~' }`
In any of the above examples, to replicate the behavior |setlocal|, use
`vim.opt_local`. Additionally, to replicate the behavior of |setglobal|, use
`vim.opt_global`.
*vim.opt*
|vim.opt| returns an Option object.
For example: `local listchar_object = vim.opt.listchar`
An `Option` has the following methods:
*vim.opt:get()*
Option:get()
Returns a lua-representation of the option. Boolean, number and string
values will be returned in exactly the same fashion.
For values that are comma-separated lists, an array will be returned with
the values as entries in the array: >
vim.cmd [[set wildignore=*.pyc,*.o]]
print(vim.inspect(vim.opt.wildignore:get()))
-- { "*.pyc", "*.o", }
for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
print("Will ignore:", ignore_pattern)
end
-- Will ignore: *.pyc
-- Will ignore: *.o
<
For values that are comma-separated maps, a table will be returned with
the names as keys and the values as entries: >
vim.cmd [[set listchars=space:_,tab:>~]]
print(vim.inspect(vim.opt.listchars:get()))
-- { space = "_", tab = ">~", }
for char, representation in pairs(vim.opt.listchars:get()) do
print(char, "->", representation)
end
<
For values that are lists of flags, a set will be returned with the flags
as keys and `true` as entries. >
vim.cmd [[set formatoptions=njtcroql]]
print(vim.inspect(vim.opt.formatoptions:get()))
-- { n = true, j = true, c = true, ... }
local format_opts = vim.opt.formatoptions:get()
if format_opts.j then
print("J is enabled!")
end
<
*vim.opt:append()*
Option:append(value)
Append a value to string-style options. See |:set+=|
These are equivalent:
`vim.opt.formatoptions:append('j')`
`vim.opt.formatoptions = vim.opt.formatoptions + 'j'`
*vim.opt:prepend()*
Option:prepend(value)
Prepend a value to string-style options. See |:set^=|
These are equivalent:
`vim.opt.wildignore:prepend('*.o')`
`vim.opt.wildignore = vim.opt.wildignore ^ '*.o'`
*vim.opt:remove()*
Option:remove(value)
Remove a value to string-style options. See |:set-=|
These are equivalent:
`vim.opt.wildignore:remove('*.pyc')`
`vim.opt.wildignore = vim.opt.wildignore - '*.pyc'`
In general, using `vim.opt` will provide the expected result when the user is
used to interacting with editor |options| via `set`. There are still times
where the user may want to set particular options via a shorthand in Lua,
which is where |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| come into play.
The behavior of |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| is designed to
follow that of |:set|, |:setlocal|, and |:setglobal| which can be seen in the
table below:
lua command global_value local_value ~
vim.o :set set set
vim.bo/vim.wo :setlocal - set
vim.go :setglobal set -
vim.o *vim.o*
Get or set editor options, like |:set|. Invalid key is an error.
@ -922,14 +1080,36 @@ vim.o *vim.o*
vim.o.cmdheight = 4
print(vim.o.columns)
vim.go *vim.go*
Get or set an |option|. Invalid key is an error.
This is a wrapper around |nvim_set_option()| and |nvim_get_option()|.
NOTE: This is different than |vim.o| because this ONLY sets the global
option, which generally produces confusing behavior for options with
|global-local| values.
Example: >
vim.go.cmdheight = 4
<
vim.bo *vim.bo*
Get or set buffer-scoped |local-options|. Invalid key is an error.
This is a wrapper around |nvim_buf_set_option()| and
|nvim_buf_get_option()|.
Example: >
vim.bo.buflisted = true
print(vim.bo.comments)
vim.wo *vim.wo*
Get or set window-scoped |local-options|. Invalid key is an error.
This is a wrapper around |nvim_win_set_option()| and
|nvim_win_get_option()|.
Example: >
vim.wo.cursorcolumn = true
print(vim.wo.foldmarker)

View File

@ -20,5 +20,12 @@ function F.npcall(fn, ...)
return F.ok_or_nil(pcall(fn, ...))
end
--- Wrap a function to return nil if it fails, otherwise the value
function F.nil_wrap(fn)
return function(...)
return F.npcall(fn, ...)
end
end
return F

631
runtime/lua/vim/_meta.lua Normal file
View File

@ -0,0 +1,631 @@
-- prevents luacheck from making lints for setting things on vim
local vim = assert(vim)
local a = vim.api
local validate = vim.validate
local SET_TYPES = setmetatable({
SET = 0,
LOCAL = 1,
GLOBAL = 2,
}, { __index = error })
local options_info = {}
for _, v in pairs(a.nvim_get_all_options_info()) do
options_info[v.name] = v
if v.shortname ~= "" then options_info[v.shortname] = v end
end
local is_global_option = function(info) return info.scope == "global" end
local is_buffer_option = function(info) return info.scope == "buf" end
local is_window_option = function(info) return info.scope == "win" end
local get_scoped_options = function(scope)
local result = {}
for name, option_info in pairs(options_info) do
if option_info.scope == scope then
result[name] = true
end
end
return result
end
local buf_options = get_scoped_options("buf")
local glb_options = get_scoped_options("global")
local win_options = get_scoped_options("win")
local function make_meta_accessor(get, set, del, validator)
validator = validator or function() return true end
validate {
get = {get, 'f'};
set = {set, 'f'};
del = {del, 'f', true};
validator = {validator, 'f'};
}
local mt = {}
function mt:__newindex(k, v)
if not validator(k) then
return
end
if del and v == nil then
return del(k)
end
return set(k, v)
end
function mt:__index(k)
if not validator(k) then
return
end
return get(k)
end
return setmetatable({}, mt)
end
vim.env = make_meta_accessor(function(k)
local v = vim.fn.getenv(k)
if v == vim.NIL then
return nil
end
return v
end, vim.fn.setenv)
do -- buffer option accessor
local function new_buf_opt_accessor(bufnr)
local function get(k)
if bufnr == nil and type(k) == "number" then
return new_buf_opt_accessor(k)
end
return a.nvim_buf_get_option(bufnr or 0, k)
end
local function set(k, v)
return a.nvim_buf_set_option(bufnr or 0, k, v)
end
return make_meta_accessor(get, set, nil, function(k)
if type(k) == 'string' then
if win_options[k] then
error(string.format([['%s' is a window option, not a buffer option. See ":help %s"]], k, k))
elseif glb_options[k] then
error(string.format([['%s' is a global option, not a buffer option. See ":help %s"]], k, k))
end
end
return true
end)
end
vim.bo = new_buf_opt_accessor(nil)
end
do -- window option accessor
local function new_win_opt_accessor(winnr)
local function get(k)
if winnr == nil and type(k) == "number" then
return new_win_opt_accessor(k)
end
return a.nvim_win_get_option(winnr or 0, k)
end
local function set(k, v)
return a.nvim_win_set_option(winnr or 0, k, v)
end
return make_meta_accessor(get, set, nil, function(k)
if type(k) == 'string' then
if buf_options[k] then
error(string.format([['%s' is a buffer option, not a window option. See ":help %s"]], k, k))
elseif glb_options[k] then
error(string.format([['%s' is a global option, not a window option. See ":help %s"]], k, k))
end
end
return true
end)
end
vim.wo = new_win_opt_accessor(nil)
end
--[[
Local window setter
buffer options: does not get copied when split
nvim_set_option(buf_opt, value) -> sets the default for NEW buffers
this sets the hidden global default for buffer options
nvim_buf_set_option(...) -> sets the local value for the buffer
set opt=value, does BOTH global default AND buffer local value
setlocal opt=value, does ONLY buffer local value
window options: gets copied
does not need to call nvim_set_option because nobody knows what the heck this does
We call it anyway for more readable code.
Command global value local value
:set option=value set set
:setlocal option=value - set
:setglobal option=value set -
--]]
local function set_scoped_option(k, v, set_type)
local info = options_info[k]
-- Don't let people do setlocal with global options.
-- That is a feature that doesn't make sense.
if set_type == SET_TYPES.LOCAL and is_global_option(info) then
error(string.format("Unable to setlocal option: '%s', which is a global option.", k))
end
-- Only `setlocal` skips setting the default/global value
-- This will more-or-less noop for window options, but that's OK
if set_type ~= SET_TYPES.LOCAL then
a.nvim_set_option(k, v)
end
if is_window_option(info) then
if set_type ~= SET_TYPES.GLOBAL then
a.nvim_win_set_option(0, k, v)
end
elseif is_buffer_option(info) then
if set_type == SET_TYPES.LOCAL
or (set_type == SET_TYPES.SET and not info.global_local) then
a.nvim_buf_set_option(0, k, v)
end
end
end
--[[
Local window getter
Command global value local value
:set option? - display
:setlocal option? - display
:setglobal option? display -
--]]
local function get_scoped_option(k, set_type)
local info = assert(options_info[k], "Must be a valid option: " .. tostring(k))
if set_type == SET_TYPES.GLOBAL or is_global_option(info) then
return a.nvim_get_option(k)
end
if is_buffer_option(info) then
local was_set, value = pcall(a.nvim_buf_get_option, 0, k)
if was_set then return value end
if info.global_local then
return a.nvim_get_option(k)
end
error("buf_get: This should not be able to happen, given my understanding of options // " .. k)
end
if is_window_option(info) then
if vim.api.nvim_get_option_info(k).was_set then
local was_set, value = pcall(a.nvim_win_get_option, 0, k)
if was_set then return value end
end
return a.nvim_get_option(k)
end
error("This fallback case should not be possible. " .. k)
end
-- vim global option
-- this ONLY sets the global option. like `setglobal`
vim.go = make_meta_accessor(a.nvim_get_option, a.nvim_set_option)
-- vim `set` style options.
-- it has no additional metamethod magic.
vim.o = make_meta_accessor(
function(k) return get_scoped_option(k, SET_TYPES.SET) end,
function(k, v) return set_scoped_option(k, v, SET_TYPES.SET) end
)
---@brief [[
--- vim.opt, vim.opt_local and vim.opt_global implementation
---
--- To be used as helpers for working with options within neovim.
--- For information on how to use, see :help vim.opt
---
---@brief ]]
--- Preserves the order and does not mutate the original list
local remove_duplicate_values = function(t)
local result, seen = {}, {}
if type(t) == "function" then error(debug.traceback("asdf")) end
for _, v in ipairs(t) do
if not seen[v] then
table.insert(result, v)
end
seen[v] = true
end
return result
end
-- TODO(tjdevries): Improve option metadata so that this doesn't have to be hardcoded.
-- Can be done in a separate PR.
local key_value_options = {
fillchars = true,
listchars = true,
winhl = true,
}
---@class OptionType
--- Option Type Enum
local OptionTypes = setmetatable({
BOOLEAN = 0,
NUMBER = 1,
STRING = 2,
ARRAY = 3,
MAP = 4,
SET = 5,
}, {
__index = function(_, k) error("Not a valid OptionType: " .. k) end,
__newindex = function(_, k) error("Cannot set a new OptionType: " .. k) end,
})
--- Convert a vimoption_T style dictionary to the correct OptionType associated with it.
---@return OptionType
local get_option_type = function(name, info)
if info.type == "boolean" then
return OptionTypes.BOOLEAN
elseif info.type == "number" then
return OptionTypes.NUMBER
elseif info.type == "string" then
if not info.commalist and not info.flaglist then
return OptionTypes.STRING
end
if key_value_options[name] then
assert(info.commalist, "Must be a comma list to use key:value style")
return OptionTypes.MAP
end
if info.flaglist then
return OptionTypes.SET
elseif info.commalist then
return OptionTypes.ARRAY
end
error("Fallthrough in OptionTypes")
else
error("Not a known info.type:" .. info.type)
end
end
--- Convert a lua value to a vimoption_T value
local convert_value_to_vim = (function()
-- Map of functions to take a Lua style value and convert to vimoption_T style value.
-- Each function takes (info, lua_value) -> vim_value
local to_vim_value = {
[OptionTypes.BOOLEAN] = function(_, value) return value end,
[OptionTypes.NUMBER] = function(_, value) return value end,
[OptionTypes.STRING] = function(_, value) return value end,
[OptionTypes.SET] = function(_, value)
if type(value) == "string" then return value end
local result = ''
for k in pairs(value) do
result = result .. k
end
return result
end,
[OptionTypes.ARRAY] = function(_, value)
if type(value) == "string" then return value end
return table.concat(remove_duplicate_values(value), ",")
end,
[OptionTypes.MAP] = function(_, value)
if type(value) == "string" then return value end
if type(value) == "function" then error(debug.traceback("asdf")) end
local result = {}
for opt_key, opt_value in pairs(value) do
table.insert(result, string.format("%s:%s", opt_key, opt_value))
end
table.sort(result)
return table.concat(result, ",")
end,
}
return function(name, info, value)
return to_vim_value[get_option_type(name, info)](info, value)
end
end)()
--- Converts a vimoption_T style value to a Lua value
local convert_value_to_lua = (function()
-- Map of OptionType to functions that take vimoption_T values and conver to lua values.
-- Each function takes (info, vim_value) -> lua_value
local to_lua_value = {
[OptionTypes.BOOLEAN] = function(_, value) return value end,
[OptionTypes.NUMBER] = function(_, value) return value end,
[OptionTypes.STRING] = function(_, value) return value end,
[OptionTypes.ARRAY] = function(_, value)
if type(value) == "table" then
value = remove_duplicate_values(value)
return value
end
return vim.split(value, ",")
end,
[OptionTypes.SET] = function(info, value)
if type(value) == "table" then return value end
assert(info.flaglist, "That is the only one I know how to handle")
local result = {}
for i = 1, #value do
result[value:sub(i, i)] = true
end
return result
end,
[OptionTypes.MAP] = function(info, raw_value)
if type(raw_value) == "table" then return raw_value end
assert(info.commalist, "Only commas are supported currently")
local result = {}
local comma_split = vim.split(raw_value, ",")
for _, key_value_str in ipairs(comma_split) do
local key, value = unpack(vim.split(key_value_str, ":"))
key = vim.trim(key)
value = vim.trim(value)
result[key] = value
end
return result
end,
}
return function(name, info, option_value)
return to_lua_value[get_option_type(name, info)](info, option_value)
end
end)()
--- Handles the mutation of various different values.
local value_mutator = function(name, info, current, new, mutator)
return mutator[get_option_type(name, info)](current, new)
end
--- Handles the '^' operator
local prepend_value = (function()
local methods = {
[OptionTypes.NUMBER] = function()
error("The '^' operator is not currently supported for")
end,
[OptionTypes.STRING] = function(left, right)
return right .. left
end,
[OptionTypes.ARRAY] = function(left, right)
for i = #right, 1, -1 do
table.insert(left, 1, right[i])
end
return left
end,
[OptionTypes.MAP] = function(left, right)
return vim.tbl_extend("force", left, right)
end,
[OptionTypes.SET] = function(left, right)
return vim.tbl_extend("force", left, right)
end,
}
return function(name, info, current, new)
return value_mutator(
name, info, convert_value_to_lua(name, info, current), convert_value_to_lua(name, info, new), methods
)
end
end)()
--- Handles the '+' operator
local add_value = (function()
local methods = {
[OptionTypes.NUMBER] = function(left, right)
return left + right
end,
[OptionTypes.STRING] = function(left, right)
return left .. right
end,
[OptionTypes.ARRAY] = function(left, right)
for _, v in ipairs(right) do
table.insert(left, v)
end
return left
end,
[OptionTypes.MAP] = function(left, right)
return vim.tbl_extend("force", left, right)
end,
[OptionTypes.SET] = function(left, right)
return vim.tbl_extend("force", left, right)
end,
}
return function(name, info, current, new)
return value_mutator(
name, info, convert_value_to_lua(name, info, current), convert_value_to_lua(name, info, new), methods
)
end
end)()
--- Handles the '-' operator
local remove_value = (function()
local remove_one_item = function(t, val)
if vim.tbl_islist(t) then
local remove_index = nil
for i, v in ipairs(t) do
if v == val then
remove_index = i
end
end
if remove_index then
table.remove(t, remove_index)
end
else
t[val] = nil
end
end
local methods = {
[OptionTypes.NUMBER] = function(left, right)
return left - right
end,
[OptionTypes.STRING] = function()
error("Subtraction not supported for strings.")
end,
[OptionTypes.ARRAY] = function(left, right)
if type(right) == "string" then
remove_one_item(left, right)
else
for _, v in ipairs(right) do
remove_one_item(left, v)
end
end
return left
end,
[OptionTypes.MAP] = function(left, right)
if type(right) == "string" then
left[right] = nil
else
for _, v in ipairs(right) do
left[v] = nil
end
end
return left
end,
[OptionTypes.SET] = function(left, right)
if type(right) == "string" then
left[right] = nil
else
for _, v in ipairs(right) do
left[v] = nil
end
end
return left
end,
}
return function(name, info, current, new)
return value_mutator(name, info, convert_value_to_lua(name, info, current), new, methods)
end
end)()
local create_option_metatable = function(set_type)
local set_mt, option_mt
local make_option = function(name, value)
local info = assert(options_info[name], "Not a valid option name: " .. name)
if type(value) == "table" and getmetatable(value) == option_mt then
assert(name == value._name, "must be the same value, otherwise that's weird.")
value = value._value
end
return setmetatable({
_name = name,
_value = value,
_info = info,
}, option_mt)
end
-- TODO(tjdevries): consider supporting `nil` for set to remove the local option.
-- vim.cmd [[set option<]]
option_mt = {
-- To set a value, instead use:
-- opt[my_option] = value
_set = function(self)
local value = convert_value_to_vim(self._name, self._info, self._value)
set_scoped_option(self._name, value, set_type)
return self
end,
get = function(self)
return convert_value_to_lua(self._name, self._info, self._value)
end,
append = function(self, right)
return self:__add(right):_set()
end,
__add = function(self, right)
return make_option(self._name, add_value(self._name, self._info, self._value, right))
end,
prepend = function(self, right)
return self:__pow(right):_set()
end,
__pow = function(self, right)
return make_option(self._name, prepend_value(self._name, self._info, self._value, right))
end,
remove = function(self, right)
return self:__sub(right):_set()
end,
__sub = function(self, right)
return make_option(self._name, remove_value(self._name, self._info, self._value, right))
end
}
option_mt.__index = option_mt
set_mt = {
__index = function(_, k)
return make_option(k, get_scoped_option(k, set_type))
end,
__newindex = function(_, k, v)
local opt = make_option(k, v)
opt:_set()
end,
}
return set_mt
end
vim.opt = setmetatable({}, create_option_metatable(SET_TYPES.SET))
vim.opt_local = setmetatable({}, create_option_metatable(SET_TYPES.LOCAL))
vim.opt_global = setmetatable({}, create_option_metatable(SET_TYPES.GLOBAL))

View File

@ -984,7 +984,7 @@ Dictionary nvim_get_all_options_info(Error *err)
/// Resulting dictionary has keys:
/// - name: Name of the option (like 'filetype')
/// - shortname: Shortened name of the option (like 'ft')
/// - type: type of option ("string", "integer" or "boolean")
/// - type: type of option ("string", "number" or "boolean")
/// - default: The default value for the option
/// - was_set: Whether the option was set.
///

View File

@ -39,6 +39,75 @@ assert(vim)
vim.inspect = package.loaded['vim.inspect']
assert(vim.inspect)
local pathtrails = {}
vim._so_trails = {}
for s in (package.cpath..';'):gmatch('[^;]*;') do
s = s:sub(1, -2) -- Strip trailing semicolon
-- Find out path patterns. pathtrail should contain something like
-- /?.so, \?.dll. This allows not to bother determining what correct
-- suffixes are.
local pathtrail = s:match('[/\\][^/\\]*%?.*$')
if pathtrail and not pathtrails[pathtrail] then
pathtrails[pathtrail] = true
table.insert(vim._so_trails, pathtrail)
end
end
function vim._load_package(name)
local basename = name:gsub('%.', '/')
local paths = {"lua/"..basename..".lua", "lua/"..basename.."/init.lua"}
for _,path in ipairs(paths) do
local found = vim.api.nvim_get_runtime_file(path, false)
if #found > 0 then
local f, err = loadfile(found[1])
return f or error(err)
end
end
for _,trail in ipairs(vim._so_trails) do
local path = "lua"..trail:gsub('?', basename) -- so_trails contains a leading slash
local found = vim.api.nvim_get_runtime_file(path, false)
if #found > 0 then
-- Making function name in Lua 5.1 (see src/loadlib.c:mkfuncname) is
-- a) strip prefix up to and including the first dash, if any
-- b) replace all dots by underscores
-- c) prepend "luaopen_"
-- So "foo-bar.baz" should result in "luaopen_bar_baz"
local dash = name:find("-", 1, true)
local modname = dash and name:sub(dash + 1) or name
local f, err = package.loadlib(found[1], "luaopen_"..modname:gsub("%.", "_"))
return f or error(err)
end
end
return nil
end
table.insert(package.loaders, 1, vim._load_package)
-- These are for loading runtime modules lazily since they aren't available in
-- the nvim binary as specified in executor.c
setmetatable(vim, {
__index = function(t, key)
if key == 'treesitter' then
t.treesitter = require('vim.treesitter')
return t.treesitter
elseif key == 'F' then
t.F = require('vim.F')
return t.F
elseif require('vim.uri')[key] ~= nil then
-- Expose all `vim.uri` functions on the `vim` module.
t[key] = require('vim.uri')[key]
return t[key]
elseif key == 'lsp' then
t.lsp = require('vim.lsp')
return t.lsp
elseif key == 'highlight' then
t.highlight = require('vim.highlight')
return t.highlight
end
end
})
vim.log = {
levels = {
TRACE = 0;
@ -105,51 +174,6 @@ function vim._os_proc_children(ppid)
return children
end
local pathtrails = {}
vim._so_trails = {}
for s in (package.cpath..';'):gmatch('[^;]*;') do
s = s:sub(1, -2) -- Strip trailing semicolon
-- Find out path patterns. pathtrail should contain something like
-- /?.so, \?.dll. This allows not to bother determining what correct
-- suffixes are.
local pathtrail = s:match('[/\\][^/\\]*%?.*$')
if pathtrail and not pathtrails[pathtrail] then
pathtrails[pathtrail] = true
table.insert(vim._so_trails, pathtrail)
end
end
function vim._load_package(name)
local basename = name:gsub('%.', '/')
local paths = {"lua/"..basename..".lua", "lua/"..basename.."/init.lua"}
for _,path in ipairs(paths) do
local found = vim.api.nvim_get_runtime_file(path, false)
if #found > 0 then
local f, err = loadfile(found[1])
return f or error(err)
end
end
for _,trail in ipairs(vim._so_trails) do
local path = "lua"..trail:gsub('?', basename) -- so_trails contains a leading slash
local found = vim.api.nvim_get_runtime_file(path, false)
if #found > 0 then
-- Making function name in Lua 5.1 (see src/loadlib.c:mkfuncname) is
-- a) strip prefix up to and including the first dash, if any
-- b) replace all dots by underscores
-- c) prepend "luaopen_"
-- So "foo-bar.baz" should result in "luaopen_bar_baz"
local dash = name:find("-", 1, true)
local modname = dash and name:sub(dash + 1) or name
local f, err = package.loadlib(found[1], "luaopen_"..modname:gsub("%.", "_"))
return f or error(err)
end
end
return nil
end
table.insert(package.loaders, 1, vim._load_package)
-- TODO(ZyX-I): Create compatibility layer.
--- Return a human-readable representation of the given object.
@ -282,32 +306,6 @@ vim.funcref = function(viml_func_name)
return vim.fn[viml_func_name]
end
-- These are for loading runtime modules lazily since they aren't available in
-- the nvim binary as specified in executor.c
local function __index(t, key)
if key == 'treesitter' then
t.treesitter = require('vim.treesitter')
return t.treesitter
elseif require('vim.uri')[key] ~= nil then
-- Expose all `vim.uri` functions on the `vim` module.
t[key] = require('vim.uri')[key]
return t[key]
elseif key == 'lsp' then
t.lsp = require('vim.lsp')
return t.lsp
elseif key == 'highlight' then
t.highlight = require('vim.highlight')
return t.highlight
elseif key == 'F' then
t.F = require('vim.F')
return t.F
end
end
setmetatable(vim, {
__index = __index
})
-- An easier alias for commands.
vim.cmd = function(command)
return vim.api.nvim_exec(command, false)
@ -315,32 +313,8 @@ end
-- These are the vim.env/v/g/o/bo/wo variable magic accessors.
do
local a = vim.api
local validate = vim.validate
local function make_meta_accessor(get, set, del)
validate {
get = {get, 'f'};
set = {set, 'f'};
del = {del, 'f', true};
}
local mt = {}
if del then
function mt:__newindex(k, v)
if v == nil then
return del(k)
end
return set(k, v)
end
else
function mt:__newindex(k, v)
return set(k, v)
end
end
function mt:__index(k)
return get(k)
end
return setmetatable({}, mt)
end
local function make_dict_accessor(scope)
validate {
scope = {scope, 's'};
@ -354,88 +328,12 @@ do
end
return setmetatable({}, mt)
end
vim.g = make_dict_accessor('g')
vim.v = make_dict_accessor('v')
vim.b = make_dict_accessor('b')
vim.w = make_dict_accessor('w')
vim.t = make_dict_accessor('t')
vim.o = make_meta_accessor(a.nvim_get_option, a.nvim_set_option)
local function getenv(k)
local v = vim.fn.getenv(k)
if v == vim.NIL then
return nil
end
return v
end
vim.env = make_meta_accessor(getenv, vim.fn.setenv)
-- TODO(ashkan) if/when these are available from an API, generate them
-- instead of hardcoding.
local window_options = {
arab = true; arabic = true; breakindent = true; breakindentopt = true;
bri = true; briopt = true; cc = true; cocu = true;
cole = true; colorcolumn = true; concealcursor = true; conceallevel = true;
crb = true; cuc = true; cul = true; cursorbind = true;
cursorcolumn = true; cursorline = true; diff = true; fcs = true;
fdc = true; fde = true; fdi = true; fdl = true;
fdm = true; fdn = true; fdt = true; fen = true;
fillchars = true; fml = true; fmr = true; foldcolumn = true;
foldenable = true; foldexpr = true; foldignore = true; foldlevel = true;
foldmarker = true; foldmethod = true; foldminlines = true; foldnestmax = true;
foldtext = true; lbr = true; lcs = true; linebreak = true;
list = true; listchars = true; nu = true; number = true;
numberwidth = true; nuw = true; previewwindow = true; pvw = true;
relativenumber = true; rightleft = true; rightleftcmd = true; rl = true;
rlc = true; rnu = true; scb = true; scl = true;
scr = true; scroll = true; scrollbind = true; signcolumn = true;
spell = true; statusline = true; stl = true; wfh = true;
wfw = true; winbl = true; winblend = true; winfixheight = true;
winfixwidth = true; winhighlight = true; winhl = true; wrap = true;
}
--@private
local function new_buf_opt_accessor(bufnr)
--@private
local function get(k)
if window_options[k] then
return a.nvim_err_writeln(k.." is a window option, not a buffer option")
end
if bufnr == nil and type(k) == "number" then
return new_buf_opt_accessor(k)
end
return a.nvim_buf_get_option(bufnr or 0, k)
end
--@private
local function set(k, v)
if window_options[k] then
return a.nvim_err_writeln(k.." is a window option, not a buffer option")
end
return a.nvim_buf_set_option(bufnr or 0, k, v)
end
return make_meta_accessor(get, set)
end
vim.bo = new_buf_opt_accessor(nil)
--@private
local function new_win_opt_accessor(winnr)
--@private
local function get(k)
if winnr == nil and type(k) == "number" then
return new_win_opt_accessor(k)
end
return a.nvim_win_get_option(winnr or 0, k)
end
--@private
local function set(k, v)
return a.nvim_win_set_option(winnr or 0, k, v)
end
return make_meta_accessor(get, set)
end
vim.wo = new_win_opt_accessor(nil)
end
--- Get a table of lines with start, end columns for a region marked by two points
@ -738,4 +636,6 @@ vim._expand_pat_get_parts = function(lua_string)
return parts, search_index
end
pcall(require, 'vim._meta')
return module

View File

@ -4883,7 +4883,7 @@ int get_option_value_strict(char *name,
if (p->flags & P_STRING) {
*stringval = xstrdup(*(char **)(varp));
} else if (p->flags & P_NUM) {
*numval = *(long *) varp;
*numval = *(long *)varp;
} else {
*numval = *(int *)varp;
}

View File

@ -1113,6 +1113,464 @@ describe('lua stdlib', function()
eq(0, funcs.luaeval "vim.wo[1000].cole")
end)
describe('vim.opt', function()
-- TODO: We still need to write some tests for optlocal, opt and then getting the options
-- Probably could also do some stuff with getting things from viml side as well to confirm behavior is the same.
it('should allow setting number values', function()
local scrolloff = exec_lua [[
vim.opt.scrolloff = 10
return vim.o.scrolloff
]]
eq(scrolloff, 10)
end)
pending('should handle STUPID window things', function()
local result = exec_lua [[
local result = {}
table.insert(result, vim.api.nvim_get_option('scrolloff'))
table.insert(result, vim.api.nvim_win_get_option(0, 'scrolloff'))
return result
]]
eq({}, result)
end)
it('should allow setting tables', function()
local wildignore = exec_lua [[
vim.opt.wildignore = { 'hello', 'world' }
return vim.o.wildignore
]]
eq(wildignore, "hello,world")
end)
it('should allow setting tables with shortnames', function()
local wildignore = exec_lua [[
vim.opt.wig = { 'hello', 'world' }
return vim.o.wildignore
]]
eq(wildignore, "hello,world")
end)
it('should error when you attempt to set string values to numeric options', function()
local result = exec_lua [[
return {
pcall(function() vim.opt.textwidth = 'hello world' end)
}
]]
eq(false, result[1])
end)
it('should error when you attempt to setlocal a global value', function()
local result = exec_lua [[
return pcall(function() vim.opt_local.clipboard = "hello" end)
]]
eq(false, result)
end)
it('should allow you to set boolean values', function()
eq({true, false, true}, exec_lua [[
local results = {}
vim.opt.autoindent = true
table.insert(results, vim.bo.autoindent)
vim.opt.autoindent = false
table.insert(results, vim.bo.autoindent)
vim.opt.autoindent = not vim.opt.autoindent:get()
table.insert(results, vim.bo.autoindent)
return results
]])
end)
it('should change current buffer values and defaults for global local values', function()
local result = exec_lua [[
local result = {}
vim.opt.makeprg = "global-local"
table.insert(result, vim.api.nvim_get_option('makeprg'))
table.insert(result, (pcall(vim.api.nvim_buf_get_option, 0, 'makeprg')))
vim.opt_local.mp = "only-local"
table.insert(result, vim.api.nvim_get_option('makeprg'))
table.insert(result, vim.api.nvim_buf_get_option(0, 'makeprg'))
vim.opt_global.makeprg = "only-global"
table.insert(result, vim.api.nvim_get_option('makeprg'))
table.insert(result, vim.api.nvim_buf_get_option(0, 'makeprg'))
vim.opt.makeprg = "global-local"
table.insert(result, vim.api.nvim_get_option('makeprg'))
table.insert(result, vim.api.nvim_buf_get_option(0, 'makeprg'))
return result
]]
-- Set -> global & local
eq("global-local", result[1])
eq(false, result[2])
-- Setlocal -> only local
eq("global-local", result[3])
eq("only-local", result[4])
-- Setglobal -> only global
eq("only-global", result[5])
eq("only-local", result[6])
-- set -> doesn't override previously set value
eq("global-local", result[7])
eq("only-local", result[8])
end)
it('should allow all sorts of string manipulation', function()
eq({'hello', 'hello world', 'start hello world'}, exec_lua [[
local results = {}
vim.opt.makeprg = "hello"
table.insert(results, vim.o.makeprg)
vim.opt.makeprg = vim.opt.makeprg + " world"
table.insert(results, vim.o.makeprg)
vim.opt.makeprg = vim.opt.makeprg ^ "start "
table.insert(results, vim.o.makeprg)
return results
]])
end)
describe('option:get()', function()
it('should work for boolean values', function()
eq(false, exec_lua [[
vim.opt.number = false
return vim.opt.number:get()
]])
end)
it('should work for number values', function()
local tabstop = exec_lua[[
vim.opt.tabstop = 10
return vim.opt.tabstop:get()
]]
eq(10, tabstop)
end)
it('should work for string values', function()
eq("hello world", exec_lua [[
vim.opt.makeprg = "hello world"
return vim.opt.makeprg:get()
]])
end)
it('should work for set type flaglists', function()
local formatoptions = exec_lua [[
vim.opt.formatoptions = 'tcro'
return vim.opt.formatoptions:get()
]]
eq(true, formatoptions.t)
eq(true, not formatoptions.q)
end)
it('should work for set type flaglists', function()
local formatoptions = exec_lua [[
vim.opt.formatoptions = { t = true, c = true, r = true, o = true }
return vim.opt.formatoptions:get()
]]
eq(true, formatoptions.t)
eq(true, not formatoptions.q)
end)
it('should work for array list type options', function()
local wildignore = exec_lua [[
vim.opt.wildignore = "*.c,*.o,__pycache__"
return vim.opt.wildignore:get()
]]
eq(3, #wildignore)
eq("*.c", wildignore[1])
end)
it('should work for key-value pair options', function()
local listchars = exec_lua [[
vim.opt.listchars = "tab:>~,space:_"
return vim.opt.listchars:get()
]]
eq({
tab = ">~",
space = "_",
}, listchars)
end)
it('should allow you to add numeric options', function()
eq(16, exec_lua [[
vim.opt.tabstop = 12
vim.opt.tabstop = vim.opt.tabstop + 4
return vim.bo.tabstop
]])
end)
it('should allow you to subtract numeric options', function()
eq(2, exec_lua [[
vim.opt.tabstop = 4
vim.opt.tabstop = vim.opt.tabstop - 2
return vim.bo.tabstop
]])
end)
end)
describe('key:value style options', function()
it('should handle dictionary style', function()
local listchars = exec_lua [[
vim.opt.listchars = {
eol = "~",
space = ".",
}
return vim.o.listchars
]]
eq("eol:~,space:.", listchars)
end)
it('should allow adding dictionary style', function()
local listchars = exec_lua [[
vim.opt.listchars = {
eol = "~",
space = ".",
}
vim.opt.listchars = vim.opt.listchars + { space = "-" }
return vim.o.listchars
]]
eq("eol:~,space:-", listchars)
end)
it('should allow adding dictionary style', function()
local listchars = exec_lua [[
vim.opt.listchars = {
eol = "~",
space = ".",
}
vim.opt.listchars = vim.opt.listchars + { space = "-" } + { space = "_" }
return vim.o.listchars
]]
eq("eol:~,space:_", listchars)
end)
it('should allow completely new keys', function()
local listchars = exec_lua [[
vim.opt.listchars = {
eol = "~",
space = ".",
}
vim.opt.listchars = vim.opt.listchars + { tab = ">>>" }
return vim.o.listchars
]]
eq("eol:~,space:.,tab:>>>", listchars)
end)
it('should allow subtracting dictionary style', function()
local listchars = exec_lua [[
vim.opt.listchars = {
eol = "~",
space = ".",
}
vim.opt.listchars = vim.opt.listchars - "space"
return vim.o.listchars
]]
eq("eol:~", listchars)
end)
it('should allow subtracting dictionary style', function()
local listchars = exec_lua [[
vim.opt.listchars = {
eol = "~",
space = ".",
}
vim.opt.listchars = vim.opt.listchars - "space" - "eol"
return vim.o.listchars
]]
eq("", listchars)
end)
it('should allow subtracting dictionary style multiple times', function()
local listchars = exec_lua [[
vim.opt.listchars = {
eol = "~",
space = ".",
}
vim.opt.listchars = vim.opt.listchars - "space" - "space"
return vim.o.listchars
]]
eq("eol:~", listchars)
end)
it('should allow adding a key:value string to a listchars', function()
local listchars = exec_lua [[
vim.opt.listchars = {
eol = "~",
space = ".",
}
vim.opt.listchars = vim.opt.listchars + "tab:>~"
return vim.o.listchars
]]
eq("eol:~,space:.,tab:>~", listchars)
end)
it('should allow prepending a key:value string to a listchars', function()
local listchars = exec_lua [[
vim.opt.listchars = {
eol = "~",
space = ".",
}
vim.opt.listchars = vim.opt.listchars ^ "tab:>~"
return vim.o.listchars
]]
eq("eol:~,space:.,tab:>~", listchars)
end)
end)
it('should automatically set when calling remove', function()
eq("foo,baz", exec_lua [[
vim.opt.wildignore = "foo,bar,baz"
vim.opt.wildignore:remove("bar")
return vim.o.wildignore
]])
end)
it('should automatically set when calling remove with a table', function()
eq("foo", exec_lua [[
vim.opt.wildignore = "foo,bar,baz"
vim.opt.wildignore:remove { "bar", "baz" }
return vim.o.wildignore
]])
end)
it('should automatically set when calling append', function()
eq("foo,bar,baz,bing", exec_lua [[
vim.opt.wildignore = "foo,bar,baz"
vim.opt.wildignore:append("bing")
return vim.o.wildignore
]])
end)
it('should automatically set when calling append with a table', function()
eq("foo,bar,baz,bing,zap", exec_lua [[
vim.opt.wildignore = "foo,bar,baz"
vim.opt.wildignore:append { "bing", "zap" }
return vim.o.wildignore
]])
end)
it('should allow adding tables', function()
local wildignore = exec_lua [[
vim.opt.wildignore = 'foo'
return vim.o.wildignore
]]
eq(wildignore, 'foo')
wildignore = exec_lua [[
vim.opt.wildignore = vim.opt.wildignore + { 'bar', 'baz' }
return vim.o.wildignore
]]
eq(wildignore, 'foo,bar,baz')
end)
it('should handle adding duplicates', function()
local wildignore = exec_lua [[
vim.opt.wildignore = 'foo'
return vim.o.wildignore
]]
eq(wildignore, 'foo')
wildignore = exec_lua [[
vim.opt.wildignore = vim.opt.wildignore + { 'bar', 'baz' }
return vim.o.wildignore
]]
eq(wildignore, 'foo,bar,baz')
wildignore = exec_lua [[
vim.opt.wildignore = vim.opt.wildignore + { 'bar', 'baz' }
return vim.o.wildignore
]]
eq(wildignore, 'foo,bar,baz')
end)
it('should allow adding multiple times', function()
local wildignore = exec_lua [[
vim.opt.wildignore = 'foo'
vim.opt.wildignore = vim.opt.wildignore + 'bar' + 'baz'
return vim.o.wildignore
]]
eq(wildignore, 'foo,bar,baz')
end)
it('should remove values when you use minus', function()
local wildignore = exec_lua [[
vim.opt.wildignore = 'foo'
return vim.o.wildignore
]]
eq(wildignore, 'foo')
wildignore = exec_lua [[
vim.opt.wildignore = vim.opt.wildignore + { 'bar', 'baz' }
return vim.o.wildignore
]]
eq(wildignore, 'foo,bar,baz')
wildignore = exec_lua [[
vim.opt.wildignore = vim.opt.wildignore - 'bar'
return vim.o.wildignore
]]
eq(wildignore, 'foo,baz')
end)
it('should prepend values when using ^', function()
local wildignore = exec_lua [[
vim.opt.wildignore = 'foo'
vim.opt.wildignore = vim.opt.wildignore ^ 'first'
return vim.o.wildignore
]]
eq('first,foo', wildignore)
wildignore = exec_lua [[
vim.opt.wildignore = vim.opt.wildignore ^ 'super_first'
return vim.o.wildignore
]]
eq(wildignore, 'super_first,first,foo')
end)
end)
it('vim.cmd', function()
exec_lua [[
vim.cmd "autocmd BufNew * ++once lua BUF = vim.fn.expand('<abuf>')"