LazyVim でファイルパスをコピーする 2

LazyVim でファイルパスをコピーするの続きです。

LazyVim で開いているファイルのパスをクリップボードにコピーします。

・相対パス cpr

ビジュアルモードの V で行選択中ならパスの後ろに選択行を追加するようにしました。OpenCode のプロンプトにペーストするときに使っています。

環境
・Omarchy v3.8.2
・LazyVim

下記を lua/config/keymaps.lua に追加します。

local function copy_path(type, range)
  local fullpath = vim.fn.expand("%:p")
  if fullpath == "" or fullpath:match("^%[.*%]$") then
    vim.notify("No file is open", vim.log.levels.WARN)
    return
  end

  local root = require("lazyvim.util").root.get({ path = fullpath })
  local path

  if type == "absolute" then
    path = fullpath
  elseif type == "relative" then
    if root and fullpath:find(root, 1, true) == 1 then
      path = fullpath:sub(#root + 2)
    else
      path = vim.fn.expand("%")
    end
  elseif type == "filename" then
    path = vim.fn.expand("%:t")
  end

  if type == "relative" and range then
    if range[1] == range[2] then
      path = path .. ":" .. range[1]
    else
      path = path .. ":" .. range[1] .. "-" .. range[2]
    end
  end

  vim.fn.setreg("+", path)
  vim.notify("Copied: " .. path, vim.log.levels.INFO)
end

vim.keymap.set("n", "<leader>cpa", function()
  copy_path("absolute")
end, { desc = "Copy absolute path" })
vim.keymap.set("n", "<leader>cpr", function()
  copy_path("relative")
end, { desc = "Copy project-relative path" })
vim.keymap.set("n", "<leader>cpf", function()
  copy_path("filename")
end, { desc = "Copy filename" })

vim.keymap.set("x", "<leader>cpr", function()
  if vim.fn.mode() ~= "V" then
    return
  end
  vim.cmd("normal! \27")
  local start_line = math.min(vim.fn.line("'<"), vim.fn.line("'>"))
  local end_line = math.max(vim.fn.line("'<"), vim.fn.line("'>"))
  copy_path("relative", { start_line, end_line })
end, { desc = "Copy project-relative path with line range" })

以上です。



▼この記事がいいね!と思ったらブックマークお願いします
このエントリーをはてなブックマークに追加