Search code examples
luaneovim

Neovim Lua: how to run a command on a visual selection?


I've got the following setup:

local function ai_edit_prompt()
    local phrase = vim.fn.input("Prompt for AI: ")
    vim.cmd(":'<,'>AIEdit " .. phrase)
end
vim.keymap.set("v", "<space>ae", ai_edit_prompt)

However, if I select some text and try to execute the ai_edit_prompt, it gives me an error about a vim mark not being found. What am I doing wrong there?

If I type it manually, like :'<,'>AIEdit convert to python array it works just fine. It's just that if I prompt for the phrase and then try to run the command on a visual selection, it fails.


Solution

  • I was able to get it to work using the following:

    vim.keymap.set("v", "<space>ae", function()
        return ":AIEdit " .. vim.fn.input("Prompt for AI: ") .. "<cr>"
    end, { expr = true })