Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to incorporate user input in an input-mode Lua keymap in Neovim?

Tags:

input

lua

neovim

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?

like image 313
Alan Avatar asked Aug 31 '25 01:08

Alan


1 Answers

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.

like image 85
Kyle F. Hartzenberg Avatar answered Sep 02 '25 16:09

Kyle F. Hartzenberg