Neovim: after the first review — exact file match, writes through the buffer, keys given back, safer approvals
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
8 files changed
+214
-28
No files matched your search
@@ -14,8 +14,18 @@ local function L() return require("llembas") end
|
||||
--- insert mode in a headless run, can say yes.
|
||||
function M._typing() return vim.api.nvim_get_mode().mode:sub(1, 1) == "i" end
|
||||
|
||||
--- The accept key is ours only while a suggestion is on the screen: a buffer mapping put there with
|
||||
--- the suggestion and taken away with it, whatever was mapped before given back as it was.
|
||||
local function unmap_accept()
|
||||
local s = st.shown
|
||||
if not s or not s.key then return end
|
||||
pcall(vim.keymap.del, "i", s.key, { buffer = s.buf })
|
||||
if s.before and next(s.before) and s.before.buffer == 1 then pcall(vim.fn.mapset, "i", false, s.before) end
|
||||
end
|
||||
|
||||
function M.clear()
|
||||
if st.shown then
|
||||
unmap_accept()
|
||||
pcall(vim.api.nvim_buf_del_extmark, st.shown.buf, ns, st.shown.mark)
|
||||
st.shown = nil
|
||||
end
|
||||
@@ -37,7 +47,13 @@ local function show(buf, row, col, text)
|
||||
opts.virt_lines = {}
|
||||
for i = 2, #lines do opts.virt_lines[#opts.virt_lines + 1] = { { lines[i], "Comment" } } end
|
||||
end
|
||||
st.shown = { buf = buf, row = row, col = col, text = text, mark = vim.api.nvim_buf_set_extmark(buf, ns, row, col, opts) }
|
||||
st.shown = { buf = buf, text = text, mark = vim.api.nvim_buf_set_extmark(buf, ns, row, col, opts) }
|
||||
local key = L().config.complete.accept
|
||||
if key and key ~= "" then
|
||||
local before = vim.fn.maparg(key, "i", false, true)
|
||||
st.shown.key, st.shown.before = key, before
|
||||
vim.keymap.set("i", key, function() M.accept() end, { buffer = buf, nowait = true, desc = "LLeMbas: accept the suggestion" })
|
||||
end
|
||||
end
|
||||
|
||||
local function usable(buf)
|
||||
@@ -64,6 +80,8 @@ function M.request(manual)
|
||||
L()._connect(function(conn)
|
||||
if seq ~= st.seq then return end
|
||||
if not conn then
|
||||
-- An agent that does not start is not started again at every pause: once a minute at most.
|
||||
st.wait_until = vim.uv.now() + 60000
|
||||
if manual then vim.notify("LLeMbas: " .. (L()._state.start_error or "the agent did not start"), vim.log.levels.WARN) end
|
||||
return
|
||||
end
|
||||
@@ -104,12 +122,16 @@ end
|
||||
function M.accept()
|
||||
local s = st.shown
|
||||
if not s or s.buf ~= vim.api.nvim_get_current_buf() then return false end
|
||||
-- Where the suggestion stands now: its mark moves with the text around it.
|
||||
local pos = vim.api.nvim_buf_get_extmark_by_id(s.buf, ns, s.mark, {})
|
||||
M.clear()
|
||||
st.seq = st.seq + 1
|
||||
if not pos[1] then return false end
|
||||
local at_row, at_col = pos[1], pos[2]
|
||||
local lines = vim.split(s.text, "\n", { plain = true })
|
||||
vim.api.nvim_buf_set_text(s.buf, s.row, s.col, s.row, s.col, lines)
|
||||
local row = s.row + #lines
|
||||
local col = #lines == 1 and (s.col + #lines[1]) or #lines[#lines]
|
||||
vim.api.nvim_buf_set_text(s.buf, at_row, at_col, at_row, at_col, lines)
|
||||
local row = at_row + #lines
|
||||
local col = #lines == 1 and (at_col + #lines[1]) or #lines[#lines]
|
||||
vim.api.nvim_win_set_cursor(0, { row, col })
|
||||
return true
|
||||
end
|
||||
@@ -130,7 +152,7 @@ function M.reset() st.off, st.said = nil, false end
|
||||
local function typed()
|
||||
M.clear()
|
||||
local c = L().config.complete
|
||||
if not c.auto or st.off then return cancel() end
|
||||
if not c.auto or st.off or (st.wait_until and vim.uv.now() < st.wait_until) then return cancel() end
|
||||
if not usable(vim.api.nvim_get_current_buf()) then return end
|
||||
cancel()
|
||||
st.timer = st.timer or vim.uv.new_timer()
|
||||
@@ -144,13 +166,6 @@ function M.setup()
|
||||
vim.api.nvim_create_autocmd({ "TextChangedI", "CursorMovedI" }, { group = group, callback = typed })
|
||||
vim.api.nvim_create_autocmd({ "InsertLeave", "BufLeave" }, { group = group, callback = function() M.clear(); cancel() end })
|
||||
local c = L().config.complete
|
||||
if c.accept and c.accept ~= "" then
|
||||
vim.keymap.set("i", c.accept, function()
|
||||
if not M.accept() then
|
||||
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(c.accept, true, false, true), "n", false)
|
||||
end
|
||||
end, { desc = "LLeMbas: accept the suggestion" })
|
||||
end
|
||||
if c.trigger and c.trigger ~= "" then
|
||||
vim.keymap.set("i", c.trigger, function() M.request(true) end, { desc = "LLeMbas: suggest here" })
|
||||
end
|
||||
|
||||
@@ -75,14 +75,46 @@ function M.editor(buf, first, last)
|
||||
return out
|
||||
end
|
||||
|
||||
--- The loaded buffer that holds exactly this file, or nil. By the full name, never by a pattern:
|
||||
--- `README` must not find `README.md`.
|
||||
function M.buffer_of(path)
|
||||
local want = vim.fs.normalize(vim.fn.fnamemodify(path, ":p"))
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
if vim.api.nvim_buf_is_loaded(b) and vim.bo[b].buftype == "" then
|
||||
local name = vim.api.nvim_buf_get_name(b)
|
||||
if name ~= "" and vim.fs.normalize(name) == want then return b end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- The agent writes a file (ACP `fs/write_text_file`): one that is open here gets the text in its
|
||||
--- buffer and is saved at once, so the buffer and the disk agree when the agent is answered. A file
|
||||
--- that is not open is refused, and the agent writes the disk itself.
|
||||
function M.write_for_agent(params, reply)
|
||||
local path, content = params.path, params.content
|
||||
if type(path) ~= "string" or type(content) ~= "string" then return reply(nil, { code = -32602, message = "no path or no text" }) end
|
||||
local buf = M.buffer_of(path)
|
||||
if not buf then return reply(nil, { code = -32002, message = "not open in the editor" }) end
|
||||
if not vim.bo[buf].modifiable or vim.bo[buf].readonly then
|
||||
return reply(nil, { code = -32002, message = "the editor holds that file read-only" })
|
||||
end
|
||||
local lines = vim.split((content:gsub("\r\n", "\n")), "\n", { plain = true })
|
||||
if lines[#lines] == "" and #lines > 1 then table.remove(lines) end
|
||||
vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
|
||||
-- Saved as it is: no autocommand (a formatter) may change what the agent believes it wrote.
|
||||
local ok, err = pcall(vim.api.nvim_buf_call, buf, function() vim.cmd("silent noautocmd write!") end)
|
||||
if not ok then return reply(nil, { code = -32002, message = "the editor could not save it: " .. tostring(err) }) end
|
||||
reply(vim.NIL)
|
||||
end
|
||||
|
||||
--- The agent asks for a file's text (ACP `fs/read_text_file`): a file open here is answered from its
|
||||
--- buffer, saved or not, so the agent sees what you see. Anything else is read from disk.
|
||||
function M.read_for_agent(params, reply)
|
||||
local path = params.path
|
||||
if type(path) ~= "string" or path == "" then return reply(nil, { code = -32602, message = "no path" }) end
|
||||
local lines
|
||||
local buf = vim.fn.bufnr(path)
|
||||
if buf ~= -1 and vim.api.nvim_buf_is_loaded(buf) and vim.bo[buf].buftype == "" then
|
||||
local buf = M.buffer_of(path)
|
||||
if buf then
|
||||
lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
|
||||
else
|
||||
local ok, read = pcall(vim.fn.readfile, path)
|
||||
|
||||
@@ -8,8 +8,13 @@ local proposals = {} -- buf -> list of pending hunks { mark, old_count, new, abo
|
||||
|
||||
local function count(buf) return #(proposals[buf] or {}) end
|
||||
|
||||
local KEYS = { "ga", "gr", "gA", "gR" }
|
||||
local saved = {} -- buf -> the buffer mappings these keys had before
|
||||
|
||||
local function unmap(buf)
|
||||
for _, k in ipairs({ "ga", "gr", "gA", "gR" }) do pcall(vim.keymap.del, "n", k, { buffer = buf }) end
|
||||
for _, k in ipairs(KEYS) do pcall(vim.keymap.del, "n", k, { buffer = buf }) end
|
||||
for _, before in ipairs(saved[buf] or {}) do pcall(vim.fn.mapset, "n", false, before) end
|
||||
saved[buf] = nil
|
||||
end
|
||||
|
||||
local function drop(buf, hunk)
|
||||
@@ -29,10 +34,17 @@ local function row_of(buf, hunk)
|
||||
end
|
||||
|
||||
local function apply(buf, hunk)
|
||||
local row = row_of(buf, hunk)
|
||||
local pos = vim.api.nvim_buf_get_extmark_by_id(buf, ns, hunk.mark, { details = true })
|
||||
local row = pos[1]
|
||||
if not row then return drop(buf, hunk) end
|
||||
if hunk.old_count > 0 then
|
||||
vim.api.nvim_buf_set_lines(buf, row, row + hunk.old_count, false, hunk.new)
|
||||
-- What the mark covers now, not what it covered when shown: lines you removed since are not removed twice.
|
||||
local last = (pos[3] or {}).end_row or row
|
||||
if last <= row then
|
||||
drop(buf, hunk)
|
||||
return vim.notify("LLeMbas: the lines of that change are gone; it was dropped", vim.log.levels.WARN)
|
||||
end
|
||||
vim.api.nvim_buf_set_lines(buf, row, last, false, hunk.new)
|
||||
elseif hunk.above then
|
||||
vim.api.nvim_buf_set_lines(buf, row, row, false, hunk.new)
|
||||
else
|
||||
@@ -116,6 +128,13 @@ function M.propose(buf, first, last, new)
|
||||
end
|
||||
table.insert(proposals[buf], hunk)
|
||||
end
|
||||
if not saved[buf] then
|
||||
saved[buf] = {}
|
||||
for _, k in ipairs(KEYS) do
|
||||
local before = vim.fn.maparg(k, "n", false, true)
|
||||
if next(before) and before.buffer == 1 then table.insert(saved[buf], before) end
|
||||
end
|
||||
end
|
||||
local function map(k, fn, desc) vim.keymap.set("n", k, fn, { buffer = buf, desc = desc, nowait = true }) end
|
||||
map("ga", function() M.accept(false) end, "LLeMbas: accept this change")
|
||||
map("gr", function() M.reject(false) end, "LLeMbas: reject this change")
|
||||
@@ -124,6 +143,11 @@ function M.propose(buf, first, last, new)
|
||||
return #hunks
|
||||
end
|
||||
|
||||
--- A buffer was reloaded from disk: what was proposed for its old text is void.
|
||||
function M.forget(buf)
|
||||
for _, h in ipairs(vim.list_slice(proposals[buf] or {})) do drop(buf, h) end
|
||||
end
|
||||
|
||||
local written = 0
|
||||
--- The agent says how far a rewrite has got.
|
||||
function M.delta(params)
|
||||
@@ -172,7 +196,7 @@ function M.preview(content)
|
||||
local out = {}
|
||||
for _, c in ipairs(content or {}) do
|
||||
if type(c) == "table" and c.type == "diff" and type(c.newText) == "string" then
|
||||
out[#out + 1] = "--- " .. tostring(c.path or "?")
|
||||
out[#out + 1] = "--- " .. (tostring(c.path or "?"):gsub("[\r\n]+", " "))
|
||||
local d = vim.diff((c.oldText or "") .. "\n", c.newText .. "\n", { result_type = "unified", ctxlen = 3 })
|
||||
vim.list_extend(out, vim.split(d ~= "" and d or "(no change)", "\n", { plain = true, trimempty = true }))
|
||||
end
|
||||
|
||||
@@ -84,6 +84,15 @@ local function on_permission(p, reply)
|
||||
local preview = require("llembas.diff").preview(call.content)
|
||||
local prompt = "LLeMbas asks: " .. (call.title or meta.tool or "a tool")
|
||||
if meta.reason then prompt = prompt .. " (" .. meta.reason .. ")" end
|
||||
-- The refusals first: the question can open while you are typing, and a digit and Enter meant for
|
||||
-- your code must not allow a command. The first choice is always a denial.
|
||||
options = vim.list_slice(options)
|
||||
table.sort(options, function(x, y)
|
||||
local dx, dy = tostring(x.kind):match("^reject") and 0 or 1, tostring(y.kind):match("^reject") and 0 or 1
|
||||
return dx < dy
|
||||
end)
|
||||
pcall(vim.cmd, "stopinsert")
|
||||
pcall(vim.cmd, "redraw")
|
||||
vim.ui.select(options, {
|
||||
prompt = prompt:gsub("[\r\n]+", " "):sub(1, 400),
|
||||
format_item = function(o) return o.name or o.optionId end,
|
||||
@@ -134,6 +143,7 @@ local function connect(cb, quiet)
|
||||
if method == "session/request_permission" then return on_permission(params, reply) end
|
||||
if method == "fs/read_text_file" then return require("llembas.context").read_for_agent(params, reply) end
|
||||
if method == "_lembas/show" then return M._show(params, reply) end
|
||||
if method == "fs/write_text_file" then return require("llembas.context").write_for_agent(params, reply) end
|
||||
reply(nil, { code = -32601, message = "Method not found: " .. method })
|
||||
end,
|
||||
-- Only the agent in use: one that was replaced (a new session) ends later and must not undo its successor.
|
||||
@@ -148,7 +158,7 @@ local function connect(cb, quiet)
|
||||
S.conn, S.ready, S.start_error = conn, false, nil
|
||||
conn:request("initialize", {
|
||||
protocolVersion = 1,
|
||||
clientCapabilities = { fs = { readTextFile = true, writeTextFile = false },
|
||||
clientCapabilities = { fs = { readTextFile = true, writeTextFile = true },
|
||||
_meta = { lembas = { editor = true, show = true, media = true } } },
|
||||
clientInfo = { name = "llembas.nvim", version = M.version },
|
||||
}, function(e1, r)
|
||||
@@ -328,8 +338,11 @@ function M.stop()
|
||||
end
|
||||
|
||||
--- A new session; the old one stays in the CLI's store.
|
||||
function M.new()
|
||||
if S.busy then return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop)", vim.log.levels.WARN) end
|
||||
function M.new(force)
|
||||
if S.busy and not force then
|
||||
return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop), or :LLeMbasNew! to end the agent", vim.log.levels.WARN)
|
||||
end
|
||||
S.busy = false
|
||||
local conn = S.conn
|
||||
S.conn, S.session, S.starting, S.connecting, S.ready, S.said = nil, nil, nil, nil, false, nil
|
||||
tools = {}
|
||||
@@ -397,8 +410,18 @@ function M._show(p, reply)
|
||||
end
|
||||
|
||||
--- Open the file the agent showed last with the system's viewer.
|
||||
-- What the system's viewer is given: files that are only looked at or listened to. Anything else
|
||||
-- (a script, a page, a shortcut, a document that can carry macros) is named and left alone.
|
||||
local VIEWED = {}
|
||||
for _, e in ipairs({ "png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "pdf", "mp3", "wav", "ogg", "oga", "flac", "m4a",
|
||||
"mp4", "webm", "mkv", "mov", "glb", "gltf", "obj", "stl", "csv", "tsv", "txt" }) do VIEWED[e] = true end
|
||||
|
||||
function M.open_shown()
|
||||
if not S.shown then return vim.notify("LLeMbas: nothing has been shown yet", vim.log.levels.INFO) end
|
||||
local ext = (S.shown:match("%.([%w]+)$") or ""):lower()
|
||||
if not VIEWED[ext] then
|
||||
return vim.notify("LLeMbas: not opened, since a file of that kind may run: " .. S.shown, vim.log.levels.WARN)
|
||||
end
|
||||
vim.ui.open(S.shown)
|
||||
end
|
||||
|
||||
@@ -485,6 +508,10 @@ vim.api.nvim_create_autocmd("VimLeavePre", {
|
||||
group = vim.api.nvim_create_augroup("llembas", { clear = true }),
|
||||
callback = function() if S.conn then S.conn:stop() end end,
|
||||
})
|
||||
vim.api.nvim_create_autocmd({ "FileChangedShellPost", "BufReadPost" }, {
|
||||
group = "llembas",
|
||||
callback = function(ev) require("llembas.diff").forget(ev.buf) end,
|
||||
})
|
||||
vim.api.nvim_create_autocmd("BufEnter", {
|
||||
group = "llembas",
|
||||
callback = function(ev) if vim.bo[ev.buf].buftype == "" then S.last_buf = ev.buf end end,
|
||||
|
||||
Reference in new issue
Block a user