feat(picker.undo): ctrl+y to yank added lines, ctrl+shift+y to yank deleted lines

This commit is contained in:
Folke Lemaitre 2025-02-07 21:58:33 +01:00
parent 1e2d8d57f1
commit 3baf95d3a1
No known key found for this signature in database
GPG key ID: 41F8B1FBACAE2040
3 changed files with 18 additions and 7 deletions

View file

@ -8,6 +8,10 @@ local M = {}
---@class snacks.picker.layout.Action: snacks.picker.Action
---@field layout? snacks.picker.layout.Config|string
---@class snacks.picker.yank.Action: snacks.picker.Action
---@field reg? string
---@field field? string
---@enum (key) snacks.picker.EditCmd
local edit_cmd = {
edit = "buffer",
@ -422,9 +426,10 @@ function M.loclist(picker)
end
function M.yank(picker, item, action)
---@cast action snacks.picker.yank.Action
if item then
local reg = action.reg or "+"
local value = item.data or item.text
local value = item[action.field] or item.data or item.text
vim.fn.setreg(reg, value)
local buf = item.buf or vim.api.nvim_win_get_buf(picker.main)
local ft = vim.bo[buf].filetype

View file

@ -803,10 +803,15 @@ M.undo = {
preview = { wo = { number = false, relativenumber = false, signcolumn = "no" } },
input = {
keys = {
["<c-y>"] = { "yank", mode = { "n", "i" } },
["<c-y>"] = { "yank_add", mode = { "n", "i" } },
["<c-s-y>"] = { "yank_del", mode = { "n", "i" } },
},
},
},
actions = {
yank_add = { action = "yank", field = "added_lines" },
yank_del = { action = "yank", field = "removed_lines" },
},
icons = { tree = { last = "┌╴" } }, -- the tree is upside down
diff = {
ctxlen = 4,

View file

@ -363,17 +363,16 @@ function M.undo(opts, ctx)
local diff = vim.diff(table.concat(before, "\n") .. "\n", table.concat(after, "\n") .. "\n", opts.diff) --[[@as string]]
local changes = {} ---@type string[]
local added, removed = 0, 0
local added_lines = {} ---@type string[]
local removed_lines = {} ---@type string[]
for _, line in ipairs(vim.split(diff, "\n")) do
if line:sub(1, 1) == "+" then
added = added + 1
changes[#changes + 1] = line:sub(2)
added_lines[#added_lines + 1] = line:sub(2)
elseif line:sub(1, 1) == "-" then
removed = removed + 1
changes[#changes + 1] = line:sub(2)
removed_lines[#removed_lines + 1] = line:sub(2)
end
end
diff = Snacks.picker.util.tpl(
@ -382,8 +381,10 @@ function M.undo(opts, ctx)
)
item.text = table.concat(changes, " ")
item.data = table.concat(added_lines, "\n")
item.added = added
item.removed = removed
item.added_lines = table.concat(added_lines, "\n")
item.removed_lines = table.concat(removed_lines, "\n")
item.added = #added_lines
item.removed = #removed_lines
item.preview = {
text = diff,
ft = "diff",