In Vim, an input mode map can use <c-r>=input()
to fetch user input and insert it at the cursor. How is this done in Neovim?
Specific Vimscript example:
imap <buffer> <unique> ;_ <c-r>="_{".input("sub:")."}"<cr>
What is the Neovim+Lua equivalent?
You can use vim.fn.input()
to get the input and store it in a Lua variable. Then get the current cursor position in the current buffer with vim.api.nvim_win_get_cursor(0)
. Finally, set the text in the current buffer at the current cursor position using vim.api.nvim_buf_set_text()
.
Here is a complete mapping:
vim.keymap.set("i", "<C-r>", function()
local user_input = vim.fn.input("Enter input: ")
local row, col = unpack(vim.api.nvim_win_get_cursor(0))
vim.api.nvim_buf_set_text(0, row - 1, col, row - 1, col, { "_{" .. user_input .. "}" })
end)
There's also the option to use vim.api.nvim_feedkeys()
to insert the text into the buffer.