KenForever1/nvim-rotate-chars采用nvim-oxi开发的nvim插件,用于旋转选中的文本字符。nvim-oxi提供了Neovim编辑器的Rust API绑定。
传统的插件方法比如:Vimscript or Lua是通过RPC channels和neovim进行通信,采用API绑定的方式。主要是避免了序列化开销,可以在同一个进程中直接调用api绑定回调函数,以及编程时提供了方便的api提示和函数解释。优势的话,相比lua可以使用rust丰富的crate库,还有编译时检查。
nvim-oxi provides safe and idiomatic Rust bindings to the rich API exposed by the Neovim text editor.The project is mostly intended for plugin authors, although nothing’s stopping end users from writing their Neovim configs in Rust.
functionprocessString(input)localboolStr,numStr=input:match("^(%S+)%s+(%S+)$")ifnotboolStrornotnumStrthenerror("Input string does not contain exactly two parts.")endlocalboolValueifboolStr:lower()=="true"thenboolValue=trueelseifboolStr:lower()=="false"thenboolValue=falseelseerror("Invalid boolean string: "..boolStr)endlocalnumValue=tonumber(numStr)ifnotnumValuethenerror("Invalid number string: "..numStr)endreturnboolValue,numValueendvim.keymap.set('v','<Leader>r',function()-- 请求用户输入数字参数vim.ui.input({prompt='Enter direction and rotation number: '},function(input)print("bool_val:"..input)localbool_val,number_arg=processString(input)print("bool_val:"..tostring(bool_val))--print("bool_val:" .. number_arg)ifnumber_arg==nilthen-- 如果输入不是有效数字,则提示错误并退出print("Error: Please enter a valid number.")returnend-- 获取选区的起始和结束行vim.cmd([[execute"normal! \<ESC>"]])localmode=vim.fn.visualmode()localstart_line=vim.fn.getpos("'<")[2]-1localend_line=vim.fn.getpos("'>")[2]print("start "..start_line.."end "..end_line)-- 调用插件的函数,将输入的数字作为参数require("nvim_rotate_chars").RotateCharsWithRange(bool_val,number_arg,start_line,end_line)end)end,{noremap=true,silent=true,desc="Rotate selected characters"})
vim.api.nvim_create_user_command('RotateChars',function(opts)-- 检查是否提供了正确数量的参数if#opts.fargs<2thenprint("Usage: :RotateChars <boolean> <number>")returnend-- 将第一个参数解析为布尔值localbool_arg=opts.fargs[1]=="true"-- 尝试将第二个参数解析为数字localnum_arg=tonumber(opts.fargs[2])ifnotnum_argthenprint("Error: The second argument must be a number.")returnend-- 调用插件的函数require("nvim_rotate_chars").RotateChars(bool_arg,num_arg)end,{range=2,nargs="+"})