Skip to content

Instantly share code, notes, and snippets.

@trentrand
Created September 1, 2023 20:38
Show Gist options
  • Save trentrand/769116620a24334d5a1ba61638ddc8eb to your computer and use it in GitHub Desktop.
Save trentrand/769116620a24334d5a1ba61638ddc8eb to your computer and use it in GitHub Desktop.
Copy relative file path of Telescope.nvim result to clipboard
-- Telescope.nvim command to copy relative path from Telescope#find_files
-- Activating <C-y> on a result will copy the path to clipboard, relative to the path of the current file Buffer
local function relative_path(target_file)
local current_file = vim.fn.expand('%:p') -- Get the full path of the current file
local target_file_full = vim.fn.fnamemodify(vim.fn.resolve(target_file), ':p') -- Get the full path of the target file
local current_parts = vim.split(current_file, '/')
local target_parts = vim.split(target_file_full, '/')
local i = 1
while i <= #current_parts and i <= #target_parts and current_parts[i] == target_parts[i] do
i = i + 1
end
local rel_parts = {}
for j = i, #current_parts - 1 do
table.insert(rel_parts, '..')
end
for j = i, #target_parts do
table.insert(rel_parts, target_parts[j])
end
local rel_path = table.concat(rel_parts, '/')
return rel_path
end
lvim.builtin.telescope.defaults.mappings = {
i = {
-- copy relative path of file
["<C-y>"] = function(prompt_bufnr)
local entry = require("telescope.actions.state").get_selected_entry()
require("telescope.actions").close(prompt_bufnr)
local value = entry.value
local rel_path = relative_path(value)
vim.fn.setreg('+', rel_path)
end,
-- ... rest of config
},
-- ... rest of config
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment