Created
October 22, 2024 22:17
-
-
Save wbbradley/0dff7987cf09c511cfb886dd55677b0c to your computer and use it in GitHub Desktop.
Snippet of destructuring clipboard in neovim Lua to find lines to populate the location list window.
This file contains 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
local function nmap(shortcut, command) | |
keymap("n", shortcut, command) | |
end | |
nmap("<leader>P", ":PopulateQuickFixFromClipboard<CR>") | |
vim.api.nvim_create_user_command("PopulateQuickFixFromClipboard", function() | |
-- Grab the contents of the system clipboard | |
local clipboard_contents = vim.fn.system("pbpaste") | |
local clipboard_lines = vim.split(clipboard_contents, "\n", { plain = true, trimempty = true }) | |
-- Define the possible formats for locations (adjust as needed) | |
local location_patterns = { | |
-- Rust cargo build output | |
{ | |
pattern = ".* ([^: ]+):(%d+):(.*)", | |
filename_group = 1, | |
lnum_group = 2, | |
description_group = "line_before", | |
}, | |
-- File paths (relative or absolute) | |
{ pattern = "^([^ :]+):(%d+):(.*)", filename_group = 1, lnum_group = 2, description_group = 3 }, | |
-- Python stack trace lines | |
{ | |
pattern = 'File (%b""), line (%d+), in (%w+)', | |
filename_group = 1, | |
lnum_group = 2, | |
description_group = 3, | |
}, | |
} | |
-- Find all the locations that match any of the patterns, and record them in a table of tables. | |
local locations = {} | |
for _, line in ipairs(clipboard_lines) do | |
for _, pattern_info in ipairs(location_patterns) do | |
local p1, p2, p3 = line:match(pattern_info.pattern) | |
if p1 then | |
local captures = { p1, p2, p3 } | |
local filename = captures[pattern_info.filename_group]:gsub('^"(.*)"$', "%1") | |
if | |
not string.find(filename, "site-packages", 1, true) | |
and not string.find(filename, "Python.framework", 1, true) | |
and not string.find(filename, "importlib", 1, true) | |
and not string.find(filename, "/rustc/", 1, true) | |
then | |
if filename:sub(1, 5) == "/app/" then | |
filename = filename:sub(6) | |
end | |
local lnum = tonumber(captures[pattern_info.lnum_group]) or 0 | |
local description = captures[pattern_info.description_group] | |
table.insert(locations, { | |
filename = filename, | |
lnum = lnum, | |
text = description, | |
}) | |
end | |
end | |
end | |
end | |
if #locations > 0 then | |
-- Populate the location list window | |
vim.fn.setqflist({}, "r", { title = "Clipboard Locations", items = locations }) | |
vim.cmd("copen") -- Open the location list window | |
vim.cmd.cfirst() | |
else | |
vim.notify("No locations found in clipboard.", vim.log.levels.INFO) | |
end | |
end, {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment