🍩

NeoVimで選択範囲の行情報をコピーしてAIに投げる

に公開

普段はNeoVimで開発をしています。Claude CodeやCodexに xxx.md の zzz行目を見てもらうということをよくやっているのですが、対象行とファイル名をNeoVim上で確認して console に貼り付けるという運用が少し面倒くさかったので、コマンドを入れてみました。

現在の行とファイル名をコピーする (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, {})

出力は下記のようになります。

at 14 in articles/copy-error-in-nvim.md

下記のようにコードを見てほしい時に使うと良さそうです。

Can you read at 14 in articles/copy-error-in-nvim.md?

選択範囲の行とファイル名をコピーする (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 another 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 })

出力は下記のようになります。

at 33-37 in articles/copy-error-in-nvim.md

下記のように特定の範囲のコードを見てほしい時に使うと良さそうです。

Can you read at 33-37 in articles/copy-error-in-nvim.md?

現在の行のエラーをコピーする (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 })

出力は下記のようになります。Claude CodeやCodexにそのまま渡すとエラーの解析を進めてくれます。

Do you know why the following error occurs at 15 in lua/plugins/lspconfig.lua?

Miss symbol `,` or `;` .

keyの登録について

keyを登録して、任意のコマンドで実行できるようにしましょう。

keymap("n", "<Leader>cl", "<cmd>CpCurrentLine<cr>")
keymap("v", "<Leader>ch", "<cmd>CpSelectedLines<cr>")
keymap("n", "<Leader>ck", "<cmd>CpError<cr>")

今回取得する文章は英語を前提としていますが、任意の文章で実行できるように調整すると良いと思います。


言いたかった英語を口で覚える暗記カードアプリ『SpeakGain』を開発しています👇

GitHubで編集を提案

Discussion