Add vim.startswith and vim.endswith (#11248)

This commit is contained in:
Ashkan Kiani 2019-12-01 05:32:55 -08:00 committed by GitHub
parent e6da21d128
commit 70b6061666
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View File

@ -320,6 +320,26 @@ function vim.pesc(s)
return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1')
end
--- Test if `prefix` is a prefix of `s` for strings.
--
-- @param s String to check
-- @param prefix Potential prefix
-- @return boolean True if prefix is a prefix of s
function vim.startswith(s, prefix)
vim.validate { s = {s, 's'}; prefix = {prefix, 's'}; }
return s:sub(1, #prefix) == prefix
end
--- Test if `suffix` is a suffix of `s` for strings.
--
-- @param s String to check
-- @param suffix Potential suffix
-- @return boolean True if suffix is a suffix of s
function vim.endswith(s, suffix)
vim.validate { s = {s, 's'}; suffix = {suffix, 's'}; }
return #suffix == 0 or s:sub(-#suffix) == suffix
end
--- Validates a parameter specification (types and values).
---
--- Usage example:

View File

@ -117,6 +117,34 @@ describe('lua stdlib', function()
eq(1, funcs.luaeval('vim.stricmp("\\0C\\0", "\\0B\\0")'))
end)
it('vim.startswith', function()
eq(true, funcs.luaeval('vim.startswith("123", "1")'))
eq(true, funcs.luaeval('vim.startswith("123", "")'))
eq(true, funcs.luaeval('vim.startswith("123", "123")'))
eq(true, funcs.luaeval('vim.startswith("", "")'))
eq(false, funcs.luaeval('vim.startswith("123", " ")'))
eq(false, funcs.luaeval('vim.startswith("123", "2")'))
eq(false, funcs.luaeval('vim.startswith("123", "1234")'))
eq("string", type(pcall_err(funcs.luaeval, 'vim.startswith("123", nil)')))
eq("string", type(pcall_err(funcs.luaeval, 'vim.startswith(nil, "123")')))
end)
it('vim.endswith', function()
eq(true, funcs.luaeval('vim.endswith("123", "3")'))
eq(true, funcs.luaeval('vim.endswith("123", "")'))
eq(true, funcs.luaeval('vim.endswith("123", "123")'))
eq(true, funcs.luaeval('vim.endswith("", "")'))
eq(false, funcs.luaeval('vim.endswith("123", " ")'))
eq(false, funcs.luaeval('vim.endswith("123", "2")'))
eq(false, funcs.luaeval('vim.endswith("123", "1234")'))
eq("string", type(pcall_err(funcs.luaeval, 'vim.endswith("123", nil)')))
eq("string", type(pcall_err(funcs.luaeval, 'vim.endswith(nil, "123")')))
end)
it("vim.str_utfindex/str_byteindex", function()
exec_lua([[_G.test_text = "xy åäö ɧ 汉语 ↥ 🤦x🦄 å بِيَّ"]])
local indicies32 = {[0]=0,1,2,3,5,7,9,10,12,13,16,19,20,23,24,28,29,33,34,35,37,38,40,42,44,46,48}