iTranslated by AI
Copying Selected Line Information in Neovim for AI
I usually develop with Neovim. I often use Claude Code or Codex to look at specific lines in my files, like xxx.md. However, the process of checking the target line and file name in Neovim and then pasting them into the console was a bit tedious, so I decided to add some commands.
Copying the current line and filename (normal mode)
api.nvim_create_user_command("CpCurrentLine", function()
local path = vim.fn.expand("%:p:.")
local line = vim.api.nvim_win_get_cursor(0)[1]
local copied = "at " .. line .. " in " .. path
vim.fn.setreg("+", copied)
vim.notify('Copied "' .. copied .. '" to the clipboard!')
end, {})
The output is as follows:
at 14 in articles/copy-error-in-nvim.md
It is useful when you want the AI to check the code, like this:
Can you read at 14 in articles/copy-error-in-nvim.md?
Copying the selected lines and filename (visual mode)
api.nvim_create_user_command("CpSelectedLines", function()
local path = vim.fn.expand("%:p:.")
local s, e = vim.fn.line("."), vim.fn.line("v")
--vim.fn.line("."): the current line in visual mode
--vim.fn.line("v"): the other end of the line in visual mode
--swap if s is greater than e
if s > e then s, e = e, s end
local lines = s .. "-" .. e
local copied = "at " .. lines .. " in " .. path
vim.fn.setreg("+", copied)
vim.notify('Copied "' .. copied .. '" to the clipboard!')
end, { range = true })
The output is as follows:
at 33-37 in articles/copy-error-in-nvim.md
It is useful when you want the AI to check a specific range of code, like this:
Can you read at 33-37 in articles/copy-error-in-nvim.md?
Copying the error on the current line (normal mode)
api.nvim_create_user_command("CpError", function()
local diags = vim.diagnostic.get(0, { lnum = vim.fn.line(".") - 1 })
if #diags == 0 then return vim.notify("No diagnostics") end
local path = vim.fn.expand("%:p:.")
local line = vim.api.nvim_win_get_cursor(0)[1]
local copied = "Do you know why the following error occurs at " ..
line .. " in " .. path .. "?\n\n" .. diags[1].message
vim.fn.setreg("+", copied)
vim.notify('Copied error messages to the clipboard!')
end, { range = true })
The output is as follows. If you pass it directly to Claude Code or Codex, they will proceed with analyzing the error.
Do you know why the following error occurs at 15 in lua/plugins/lspconfig.lua?
Miss symbol `,` or `;` .
Registering Keymaps
Let's register keymaps so that you can execute these commands whenever you like.
keymap("n", "<Leader>cl", "<cmd>CpCurrentLine<cr>")
keymap("v", "<Leader>ch", "<cmd>CpSelectedLines<cr>")
keymap("n", "<Leader>ck", "<cmd>CpError<cr>")
The text generated here assumes English, but it would be a good idea to adjust it so that it can be used with any text.
Discussion