Created
September 1, 2023 20:38
-
-
Save trentrand/769116620a24334d5a1ba61638ddc8eb to your computer and use it in GitHub Desktop.
Copy relative file path of Telescope.nvim result to clipboard
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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