我一直在尝试创建一个 Lua 函数,允许我克隆 Neovim 缓冲区。这是我的
init.lua
文件中的内容:
-- Set max optimum columns
vim.opt.colorcolumn = "80"
-- function to clone buffers
Clone_buffer = function()
local rfp = vim.fn.expand("%:h")
local ft = vim.bo.filetype
vim.cmd(string.format("%s" .. "/copy" .. ".%s", rfp, ft))
end
我已经映射了它,但每次使用它时都会出现下一个错误:
E5108: Error executing lua vim/_editor.lua:0: nvim_exec2(): Vim(lua):E5107: Error loading lua [string ":lua"]:1: unexpected symbol near '/'
stack traceback:
[C]: in function 'nvim_exec2'
vim/_editor.lua: in function 'cmd'
~/.config/nvim/lua/custom/init.lua:7: in function 'Clone_buffer'
[string ":lua"]:1: in main chunk
我不知道
unexpected symbol near '/'
是什么意思。如果有人可以帮助我,我将不胜感激。
我也尝试将“/copy”更改为“copy”,但引发了相同的异常,所以我认为它与
rfp
和 ft
变量有关。
不清楚您打算如何选择要克隆的缓冲区,也不清楚您希望克隆(复制)的版本去往何处。我假设您想要克隆当前缓冲区并将内容输出到当前缓冲区的当前工作目录中的重复文件。按
Alt
+d
后,解决方案如下:
local function inc_file_name_until_unique(path_to_file)
-- Get the file name (with extension)
local file_name = string.match(path_to_file, "[^/]+$")
-- Get the file extension
local file_ext = string.match(path_to_file, "[.][^.]+$")
-- Get the file name (without extension) (use gsub to escape Lua magic characters with "%" symbol)
local file_name_wo_ext = string.gsub(file_name, file_ext:gsub("%W", "%%%1"), "")
-- Get the directory of the file (use gsub to escape Lua magic characters with "%" symbol)
local file_path = string.gsub(path_to_file, file_name:gsub("%W", "%%%1"), "")
local inc = 1
-- Create new file name
local new_file_name = file_path .. file_name_wo_ext .. "-clone" .. tostring(inc) .. file_ext
-- Check new file name is unique, if not, increment its counter until it is
while vim.fn.filereadable(new_file_name) == 1 do
inc = inc + 1
new_file_name = file_path .. file_name_wo_ext .. "-clone" .. tostring(inc) .. file_ext
end
return new_file_name
end
local function clone_buffer()
local curr_bufnr = vim.api.nvim_get_current_buf()
local curr_buf_content = vim.api.nvim_buf_get_lines(curr_bufnr, 0, -1, false)
local curr_buf_content_str = table.concat(curr_buf_content, "\n")
local curr_buf_name = vim.api.nvim_buf_get_name(curr_bufnr)
local clone_name = inc_file_name_until_unique(curr_buf_name)
local clone_file = io.output(clone_name)
clone_file:write(curr_buf_content_str)
clone_file:close()
vim.api.nvim_echo({{"Cloned current buffer to \"" .. clone_name .. "\""}}, false, {})
end
vim.keymap.set({'n'}, '<A-d>', '', {
callback = clone_buffer
})