Neovim: the four bars — top, bottom, tree, and the right bar with settings lines, chat and prompt
One table of keys binds every action in two forms (the terminal's chords, and keys that always arrive), and the bottom bar shows the form that works for the bar that has the focus. The prompt says what Enter will do (ask, rewrite, add; Tab switches in an empty prompt) and carries the selection or the cursor's line as its attachment. Mode, effort, suggestions, AI on or off and the bars are remembered per directory with a machine-wide default. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
15 files changed
+3261
-46
No files matched your search
+115
-16
@@ -5,7 +5,11 @@ local ui = require("llembas.ui")
|
||||
local M = {
|
||||
tbuf = nil, ibuf = nil, marks = {}, details = {},
|
||||
on_send = nil, on_stop = nil, on_help = nil, on_files = nil, on_commands = nil,
|
||||
on_intent = nil, on_back = nil,
|
||||
bars = false, -- opened as the right bar of the layout: settings lines above, Enter sends, Esc goes back
|
||||
intent = "ask", -- what Enter will do, shown before the prompt's first line
|
||||
}
|
||||
M.PREFIX_WIDTH = 10 -- "rewrite › ", the longest; every prefix is padded to it
|
||||
local ns = vim.api.nvim_create_namespace("llembas")
|
||||
local ns_hl = vim.api.nvim_create_namespace("llembas-hl")
|
||||
local ns_welcome = vim.api.nvim_create_namespace("llembas-welcome")
|
||||
@@ -30,7 +34,7 @@ local function sync_welcome()
|
||||
vim.api.nvim_buf_clear_namespace(M.tbuf, ns_welcome, 0, -1)
|
||||
if is_empty_buf(M.tbuf) then
|
||||
vim.api.nvim_buf_set_extmark(M.tbuf, ns_welcome, 0, 0, {
|
||||
virt_lines = ui.welcome_virt_lines(),
|
||||
virt_lines = ui.welcome_virt_lines(M.bars),
|
||||
virt_lines_above = false,
|
||||
})
|
||||
end
|
||||
@@ -127,15 +131,15 @@ local function buffers()
|
||||
M.details = {}
|
||||
vim.keymap.set("n", "q", function() M.close() end, { buffer = M.tbuf, desc = "LLeMbas: close the panel" })
|
||||
vim.keymap.set("n", "<C-c>", function() if M.on_stop then M.on_stop() end end, { buffer = M.tbuf, desc = "LLeMbas: stop the turn" })
|
||||
vim.keymap.set("n", "<CR>", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" })
|
||||
vim.keymap.set("n", "gf", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" })
|
||||
vim.keymap.set("n", "K", inspect_line, { buffer = M.tbuf, desc = "LLeMbas: inspect tool output" })
|
||||
vim.keymap.set("n", "y", yank_code_block, { buffer = M.tbuf, desc = "LLeMbas: yank code block under cursor" })
|
||||
vim.keymap.set("n", "g?", function() if M.on_help then M.on_help() end end, { buffer = M.tbuf, desc = "LLeMbas: help" })
|
||||
vim.keymap.set("n", "i", function()
|
||||
local iw = win_of(M.ibuf)
|
||||
if iw then vim.api.nvim_set_current_win(iw); pcall(vim.cmd, "startinsert") end
|
||||
end, { buffer = M.tbuf, desc = "LLeMbas: jump to prompt" })
|
||||
require("llembas.keys").bind("chat", M.tbuf, {
|
||||
chat_open = open_at_cursor,
|
||||
chat_output = inspect_line,
|
||||
chat_prompt = function() M.focus_prompt() end,
|
||||
})
|
||||
vim.b[M.tbuf].completion = false -- no completion menu in a buffer nobody types in
|
||||
sync_welcome()
|
||||
end
|
||||
if not valid(M.ibuf) then
|
||||
@@ -145,7 +149,33 @@ local function buffers()
|
||||
if not text:match("%S") then return end
|
||||
if M.on_send and M.on_send(text) ~= false then vim.api.nvim_buf_set_lines(M.ibuf, 0, -1, false, {}) end
|
||||
end
|
||||
vim.keymap.set("n", "<CR>", send, { buffer = M.ibuf, desc = "LLeMbas: send" })
|
||||
local function key(k) vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(k, true, false, true), "n", false) end
|
||||
local function empty()
|
||||
return not table.concat(vim.api.nvim_buf_get_lines(M.ibuf, 0, -1, false), ""):match("%S")
|
||||
end
|
||||
-- The prompt's keys are the key table's (scope "prompt"). <Tab> has one job here: in an empty
|
||||
-- prompt it switches what Enter will do; with text in the prompt it is Neovim's own Tab.
|
||||
-- In the layout's right bar Enter sends from insert mode too (<C-j> is the new line) and
|
||||
-- Esc goes back to the code; in the panel on its own they stay Neovim's.
|
||||
require("llembas.keys").bind("prompt", M.ibuf, {
|
||||
send = function()
|
||||
if vim.api.nvim_get_mode().mode:sub(1, 1) == "i" and not M.bars then return key("<CR>") end
|
||||
send()
|
||||
end,
|
||||
intent = function()
|
||||
if empty() then
|
||||
if M.on_intent then M.on_intent() end
|
||||
elseif vim.api.nvim_get_mode().mode:sub(1, 1) == "i" then
|
||||
key("<Tab>")
|
||||
end
|
||||
end,
|
||||
newline = function() key("<CR>") end,
|
||||
back = function()
|
||||
if not M.bars then return key("<Esc>") end
|
||||
if M.on_back then M.on_back() end
|
||||
end,
|
||||
}, { send = { "n", "i" }, intent = { "n", "i" }, newline = "i", back = { "n", "i" } })
|
||||
vim.b[M.ibuf].completion = false -- the prompt is one line of words, not code: no menu over it
|
||||
vim.keymap.set({ "n", "i" }, "<C-s>", send, { buffer = M.ibuf, desc = "LLeMbas: send" })
|
||||
vim.keymap.set({ "n", "i" }, "<C-c>", function() if M.on_stop then M.on_stop() end end, { buffer = M.ibuf, desc = "LLeMbas: stop the turn" })
|
||||
vim.keymap.set("n", "q", function() M.close() end, { buffer = M.ibuf, desc = "LLeMbas: close the panel" })
|
||||
@@ -161,9 +191,56 @@ end
|
||||
|
||||
function M.is_open() return win_of(M.tbuf) ~= nil end
|
||||
|
||||
--- Open the panel (`opts` may be a width number or `{ width, position, prompt_height, border }`).
|
||||
--- What stands before the prompt's first line: what Enter will do. Every prefix has the same
|
||||
--- width, and the lines under the first are indented by it, so the text has one left edge.
|
||||
function M.prefix()
|
||||
if vim.v.lnum == 1 and vim.v.virtnum == 0 then
|
||||
local word = M.intent .. " ›"
|
||||
return "%#LLeMbasPromptPrefix#" .. word .. (" "):rep(M.PREFIX_WIDTH - vim.fn.strdisplaywidth(word)) .. "%*"
|
||||
end
|
||||
return (" "):rep(M.PREFIX_WIDTH)
|
||||
end
|
||||
|
||||
--- What Enter will do: "ask", "rewrite" or "add". The prefix shows it.
|
||||
function M.set_intent(intent)
|
||||
M.intent = intent
|
||||
local w = win_of(M.ibuf)
|
||||
if w then
|
||||
if not pcall(vim.api.nvim__redraw, { win = w, statuscolumn = true }) then pcall(vim.cmd, "redraw!") end
|
||||
end
|
||||
end
|
||||
|
||||
--- The focus into the prompt, typing.
|
||||
function M.focus_prompt()
|
||||
local iw = win_of(M.ibuf)
|
||||
if not iw then return false end
|
||||
vim.api.nvim_set_current_win(iw)
|
||||
pcall(vim.cmd, "startinsert!")
|
||||
return true
|
||||
end
|
||||
|
||||
--- No `~` under the text of a bar: the rows past the end are empty.
|
||||
local function quiet_end(win)
|
||||
local fc = vim.wo[win].fillchars
|
||||
if not fc:find("eob:", 1, true) then vim.wo[win].fillchars = (fc ~= "" and (fc .. ",") or "") .. "eob: " end
|
||||
end
|
||||
|
||||
local function prompt_options(iw)
|
||||
if M.bars then quiet_end(iw) end
|
||||
-- The prefix is the window's status column: the number column's place, with our text in it.
|
||||
vim.wo[iw].number = true
|
||||
vim.wo[iw].numberwidth = 1
|
||||
vim.wo[iw].statuscolumn = "%{%v:lua.require'llembas.chat'.prefix()%}"
|
||||
vim.wo[iw].foldcolumn = "0"
|
||||
end
|
||||
|
||||
--- Open the panel (`opts` may be a width number or `{ width, position, prompt_height, border }`;
|
||||
--- `bars = true` opens it as the layout's right bar: `lines = true` puts the settings lines above
|
||||
--- the transcript).
|
||||
function M.open(opts, focus)
|
||||
M.bars = type(opts) == "table" and opts.bars == true
|
||||
buffers()
|
||||
sync_welcome()
|
||||
local width = type(opts) == "number" and opts or (opts and opts.width) or 64
|
||||
local position = type(opts) == "table" and opts.position or "right"
|
||||
local prompt_h = type(opts) == "table" and opts.prompt_height or 5
|
||||
@@ -206,27 +283,45 @@ function M.open(opts, focus)
|
||||
else vim.cmd("botright vertical " .. width .. "split") end
|
||||
tw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(tw, M.tbuf)
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixwidth = position ~= "bottom" }) do
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixwidth = position ~= "bottom",
|
||||
statuscolumn = "", foldcolumn = "0", list = false, cursorline = false }) do
|
||||
vim.wo[tw][k] = v
|
||||
end
|
||||
if M.bars and type(opts) == "table" and opts.lines then
|
||||
local lines = require("llembas.lines")
|
||||
vim.cmd("aboveleft " .. lines.height() .. "split")
|
||||
local sw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(sw, lines.buffer())
|
||||
for k, v in pairs({ wrap = false, number = false, relativenumber = false, signcolumn = "no", winfixheight = true, winfixwidth = true,
|
||||
statuscolumn = "", foldcolumn = "0", list = false, cursorline = true, winbar = "" }) do
|
||||
vim.wo[sw][k] = v
|
||||
end
|
||||
lines.render()
|
||||
quiet_end(sw)
|
||||
vim.api.nvim_set_current_win(tw)
|
||||
end
|
||||
if M.bars then quiet_end(tw) end
|
||||
end
|
||||
if not iw then
|
||||
vim.api.nvim_set_current_win(tw)
|
||||
vim.cmd("belowright " .. prompt_h .. "split")
|
||||
-- In the layout the height is the prompt's own rows: the chip's row is one more.
|
||||
vim.cmd("belowright " .. (M.bars and prompt_h + 1 or prompt_h) .. "split")
|
||||
iw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(iw, M.ibuf)
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixheight = true }) do
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixheight = true,
|
||||
winfixwidth = position ~= "bottom", list = false, cursorline = false }) do
|
||||
vim.wo[iw][k] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
if iw and vim.api.nvim_win_is_valid(iw) then prompt_options(iw) end
|
||||
|
||||
if focus == false and vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back)
|
||||
elseif iw and vim.api.nvim_win_is_valid(iw) then vim.api.nvim_set_current_win(iw) end
|
||||
end
|
||||
|
||||
function M.close()
|
||||
for _, b in ipairs({ M.ibuf, M.tbuf }) do
|
||||
for _, b in ipairs({ M.ibuf, M.tbuf, require("llembas.lines").buf() }) do
|
||||
local w = win_of(b)
|
||||
if w and #vim.api.nvim_tabpage_list_wins(0) > 1 then pcall(vim.api.nvim_win_close, w, true) end
|
||||
end
|
||||
@@ -235,13 +330,17 @@ end
|
||||
--- The header line above the transcript: brand, session title, mode, model, usage.
|
||||
function M.header(text)
|
||||
local w = win_of(M.tbuf)
|
||||
if w then vim.wo[w].winbar = (text or ""):gsub("%%", "%%%%") end
|
||||
-- In the layout the top bar says all of this: the transcript has no line of its own.
|
||||
if w then vim.wo[w].winbar = M.bars and "" or (text or ""):gsub("%%", "%%%%") end
|
||||
end
|
||||
|
||||
--- The line above the prompt: what the next message carries, the mode, the model.
|
||||
function M.status(text)
|
||||
function M.status(text, hl)
|
||||
local w = win_of(M.ibuf)
|
||||
if w then vim.wo[w].winbar = (text or ""):gsub("%%", "%%%%") end
|
||||
if not w then return end
|
||||
-- Never empty: the row is there with or without an attachment, so the prompt does not move.
|
||||
local shown = ((text and text ~= "") and text or " "):gsub("%%", "%%%%")
|
||||
vim.wo[w].winbar = (hl and text and text ~= "") and ("%#" .. hl .. "#" .. shown .. "%*") or shown
|
||||
end
|
||||
|
||||
local function edit(fn)
|
||||
|
||||
@@ -125,6 +125,7 @@ local function show(buf, row, col, text)
|
||||
st.shown.maps[#st.shown.maps + 1] = { key = key, before = before }
|
||||
vim.keymap.set("i", key, fn, { buffer = buf, nowait = true, desc = desc })
|
||||
end
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
bind(c.accept, function() M.accept() end, "LLeMbas: accept the suggestion")
|
||||
if c.accept_word and c.accept_word ~= "" and c.accept_word ~= c.accept then
|
||||
bind(c.accept_word, function() M.accept_word() end, "LLeMbas: accept next word of suggestion")
|
||||
@@ -179,6 +180,10 @@ end
|
||||
function M.request(manual)
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
if not usable(buf) then return end
|
||||
if L()._state.ai == false then
|
||||
if manual then say("no suggestion: LLeMbas is off", true) end
|
||||
return
|
||||
end
|
||||
local win = vim.api.nvim_get_current_win()
|
||||
local pos = vim.api.nvim_win_get_cursor(win)
|
||||
local row, col = pos[1] - 1, pos[2]
|
||||
@@ -331,7 +336,7 @@ function M.why() return st.why end
|
||||
local function typed()
|
||||
M.clear()
|
||||
local c = L().config.complete
|
||||
if not c.auto or st.off or (st.wait_until and vim.uv.now() < st.wait_until) then return cancel() end
|
||||
if not c.auto or st.off or L()._state.ai == false 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()
|
||||
|
||||
@@ -29,6 +29,7 @@ local function drop(buf, hunk)
|
||||
if #list == 0 then
|
||||
proposals[buf] = nil
|
||||
unmap(buf)
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
end
|
||||
end
|
||||
|
||||
@@ -169,9 +170,12 @@ function M.propose(buf, first, last, new)
|
||||
virt_lines = virt(lines), virt_lines_above = hunk.above, right_gravity = false })
|
||||
end
|
||||
if i == 1 and hint_row then
|
||||
-- The keys as the key table has them, in the form that arrives in this terminal.
|
||||
local K = require("llembas.keys")
|
||||
local function key(id) return K.shown(K.by_id[id]) end
|
||||
local label = #hunks > 1
|
||||
and (" ◈ LLeMbas (%d changes): ga accept · gr reject · gA/gR all · ]h/[h jump"):format(#hunks)
|
||||
or " ◈ LLeMbas: ga accept · gr reject"
|
||||
and (" ◈ LLeMbas (%d changes): %s accept · %s reject · %s all · %s next"):format(#hunks, key("accept"), key("reject"), key("accept_all"), key("next_change"))
|
||||
or (" ◈ LLeMbas: %s accept · %s reject"):format(key("accept"), key("reject"))
|
||||
hunk.hint = vim.api.nvim_buf_set_extmark(buf, ns, hint_row, 0, {
|
||||
virt_text = { { label, "LLeMbasDiffHint" } },
|
||||
virt_text_pos = "eol",
|
||||
@@ -186,13 +190,16 @@ function M.propose(buf, first, last, new)
|
||||
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")
|
||||
map("gA", function() M.accept(true) end, "LLeMbas: accept all changes")
|
||||
map("gR", function() M.reject(true) end, "LLeMbas: reject all changes")
|
||||
map("]h", function() M.next_hunk() end, "LLeMbas: next proposed change")
|
||||
map("[h", function() M.prev_hunk() end, "LLeMbas: previous proposed change")
|
||||
-- The buffer's own keys while changes are shown: the key table's (scope "change").
|
||||
require("llembas.keys").bind("change", buf, {
|
||||
accept = function() M.accept(false) end,
|
||||
reject = function() M.reject(false) end,
|
||||
accept_all = function() M.accept(true) end,
|
||||
reject_all = function() M.reject(true) end,
|
||||
next_change = function() M.next_hunk() end,
|
||||
prev_change = function() M.prev_hunk() end,
|
||||
})
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
return #hunks
|
||||
end
|
||||
|
||||
|
||||
+462
-14
@@ -5,6 +5,7 @@ local rpc = require("llembas.rpc")
|
||||
local chat = require("llembas.chat")
|
||||
local context = require("llembas.context")
|
||||
local ui = require("llembas.ui")
|
||||
local store = require("llembas.store")
|
||||
|
||||
local M = {}
|
||||
|
||||
@@ -133,6 +134,9 @@ M.config = {
|
||||
accept_word = "<M-Right>", -- accepts the next word of a shown suggestion
|
||||
trigger = "<M-\\>", -- asks for a suggestion now
|
||||
},
|
||||
keys = false, -- true, or { prefix = "<Leader>l", chords = nil | true | false }: map the keys
|
||||
bars = false, -- true, or a table (see |llembas-bars|): the four-bar layout
|
||||
remember = true, -- keep the mode, effort, on/off and the bars per directory
|
||||
}
|
||||
|
||||
local S = {
|
||||
@@ -140,8 +144,38 @@ local S = {
|
||||
modes = {}, mode = nil, model = nil, title = nil, progress = nil, usage = nil, team = nil, commands = {},
|
||||
attached = nil, attached_label = nil, last_buf = nil, said = nil, shown = nil,
|
||||
cwd = nil, cli = nil, last_stderr = nil,
|
||||
effort = nil, ctx = nil, activity = nil, intent = "ask", target = nil, ai = true, signed_out = false,
|
||||
}
|
||||
|
||||
--- What is remembered for this directory (|llembas-remembered|), read once and after each change.
|
||||
local kept
|
||||
local function remembered()
|
||||
if not kept then kept = store.get() end
|
||||
return kept
|
||||
end
|
||||
local function remember(key, value)
|
||||
store.set(key, value)
|
||||
kept = nil
|
||||
end
|
||||
|
||||
local changed_pending = false
|
||||
--- Something a bar shows has changed: `User LLeMbasChanged`, once per turn of the event loop.
|
||||
local function changed()
|
||||
if changed_pending then return end
|
||||
changed_pending = true
|
||||
vim.schedule(function()
|
||||
changed_pending = false
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
end)
|
||||
end
|
||||
|
||||
local function bars_on()
|
||||
local ok, on = pcall(function() return require("llembas.layout")._state.on end)
|
||||
return ok and on == true
|
||||
end
|
||||
|
||||
local OFF = "LLeMbas is off: nothing is sent, nothing is asked. :LLeMbasAI on turns it on."
|
||||
|
||||
--- Whether an error of the agent's says that the CLI is not signed in to a server.
|
||||
local function not_signed_in(err)
|
||||
local code = code_of(err)
|
||||
@@ -219,7 +253,13 @@ local function status()
|
||||
end
|
||||
chat.header(" " .. table.concat(top, " · "))
|
||||
|
||||
changed()
|
||||
if chat.bars then
|
||||
-- In the layout the bars say the rest: the line above the prompt is the attachment's chip.
|
||||
return chat.status(S.attached_label and (" " .. S.attached_label .. " ") or "", "LLeMbasChip")
|
||||
end
|
||||
local parts = {}
|
||||
if S.intent ~= "ask" then parts[#parts + 1] = S.intent end
|
||||
if S.attached_label then parts[#parts + 1] = "with " .. S.attached_label end
|
||||
if S.mode then parts[#parts + 1] = "mode " .. S.mode end
|
||||
if S.model then parts[#parts + 1] = S.model end
|
||||
@@ -259,9 +299,11 @@ end
|
||||
local function on_update(u)
|
||||
local kind = u.sessionUpdate
|
||||
if kind == "agent_message_chunk" then
|
||||
if S.activity ~= "writing" then S.activity = "writing"; changed() end
|
||||
if S.said ~= "agent" then chat.section("LLeMbas", "LLeMbasAgentHeader"); S.said = "agent" end
|
||||
if u.content and u.content.type == "text" then chat.append(u.content.text) end
|
||||
elseif kind == "agent_thought_chunk" then
|
||||
if S.activity ~= "thinking" then S.activity = "thinking"; changed() end
|
||||
if M.config.show_thoughts and u.content and u.content.type == "text" then
|
||||
if S.said ~= "thought" then chat.section("Thinking", "LLeMbasThoughtHeader"); S.said = "thought" end
|
||||
chat.append(u.content.text, "LLeMbasThought")
|
||||
@@ -278,6 +320,8 @@ local function on_update(u)
|
||||
if text_out ~= "" then t.output = text_out:sub(1, 20000) end
|
||||
chat.line("tool:" .. id, render_tool_line(t), tool_hl(t), t.output)
|
||||
S.said = "tool"
|
||||
local doing = (t.status == "completed" or t.status == "failed") and "thinking" or "tools"
|
||||
if S.activity ~= doing then S.activity = doing; changed() end
|
||||
if t.status == "completed" then reload_files() end
|
||||
elseif kind == "plan" then
|
||||
local entries = u.entries or {}
|
||||
@@ -330,6 +374,7 @@ local function on_permission(p, reply)
|
||||
local who = meta.subagent and meta.subagent.name and (" [" .. meta.subagent.name .. "]") or ""
|
||||
chat.line(line_id, "- ? " .. (call.title or meta.tool or "a tool") .. who .. " (waits for your answer)", "LLeMbasToolPending")
|
||||
pending_cards[call_id] = { line_id = line_id, title = call.title or meta.tool or "a tool" }
|
||||
changed()
|
||||
local preview = require("llembas.diff").preview(call.content)
|
||||
local prompt = "LLeMbas asks" .. who .. ": " .. (call.title or meta.tool or "a tool")
|
||||
if meta.reason then prompt = prompt .. " (" .. meta.reason .. ")" end
|
||||
@@ -350,6 +395,7 @@ local function on_permission(p, reply)
|
||||
-- Taken down meanwhile (answered elsewhere, or no longer waited for): there is nobody to tell.
|
||||
if not pending_cards[call_id] then return end
|
||||
pending_cards[call_id] = nil
|
||||
changed()
|
||||
if not choice then
|
||||
chat.line(line_id, "- ✗ " .. (call.title or "a tool") .. " (not answered: denied)", "LLeMbasToolFail")
|
||||
return reply({ outcome = { outcome = "cancelled" } })
|
||||
@@ -366,12 +412,14 @@ local function on_question(p, reply)
|
||||
local id = "q:" .. call_id
|
||||
chat.line(id, "- ? " .. (p.why or (qs[1] and qs[1].question) or "question") .. " (waits for your answer)", "LLeMbasToolPending")
|
||||
pending_cards[call_id] = { line_id = id, title = "question" }
|
||||
changed()
|
||||
pcall(vim.cmd, "stopinsert")
|
||||
local answers = {}
|
||||
local summaries = {}
|
||||
local function done_all()
|
||||
if not pending_cards[call_id] then return end
|
||||
pending_cards[call_id] = nil
|
||||
changed()
|
||||
local summary = table.concat(summaries, " · ")
|
||||
chat.line(id, "- ✓ answered question" .. (summary ~= "" and (": " .. summary) or ""), "LLeMbasToolDone")
|
||||
return reply({ outcome = "answered", answers = answers })
|
||||
@@ -379,6 +427,7 @@ local function on_question(p, reply)
|
||||
local function dismiss_all()
|
||||
if not pending_cards[call_id] then return end
|
||||
pending_cards[call_id] = nil
|
||||
changed()
|
||||
chat.line(id, "- ✗ question dismissed", "LLeMbasToolDenied")
|
||||
return reply({ outcome = "dismissed" })
|
||||
end
|
||||
@@ -500,6 +549,7 @@ local function on_plan(p, reply)
|
||||
if type(p.text) == "string" and p.text ~= "" then chat.append(p.text .. "\n") end
|
||||
chat.line(id, "- ? " .. title .. " (waits for approval)", "LLeMbasToolPending")
|
||||
pending_cards[call_id] = { line_id = id, title = title }
|
||||
changed()
|
||||
pcall(vim.cmd, "stopinsert")
|
||||
local actions = {
|
||||
{ id = "dismiss", label = "Dismiss" },
|
||||
@@ -513,6 +563,7 @@ local function on_plan(p, reply)
|
||||
}, function(choice)
|
||||
if not pending_cards[call_id] then return end
|
||||
pending_cards[call_id] = nil
|
||||
changed()
|
||||
if not choice or choice.id == "dismiss" then
|
||||
chat.line(id, "- ✗ plan dismissed", "LLeMbasToolDenied")
|
||||
return reply({ outcome = "dismissed" })
|
||||
@@ -588,6 +639,11 @@ end
|
||||
--- Have a running agent that has answered `initialize`, then call `cb(true)`; `cb(false)` when not.
|
||||
--- `quiet`: a failure is not written into the chat (completion asks often and must not nag).
|
||||
local function connect(cb, quiet)
|
||||
if not S.ai then
|
||||
S.start_error = OFF
|
||||
if not quiet then vim.notify(OFF, vim.log.levels.INFO) end
|
||||
return cb(false)
|
||||
end
|
||||
if S.conn and S.ready then return cb(true) end
|
||||
if S.connecting then S.connecting[#S.connecting + 1] = cb; return end
|
||||
S.connecting = { cb }
|
||||
@@ -617,13 +673,18 @@ local function connect(cb, quiet)
|
||||
end
|
||||
elseif method == "_lembas/event" and params.sessionId == S.session and params.event then
|
||||
local ev = params.event
|
||||
if ev.type == "model" and type(ev.ref) == "string" then S.model = ev.ref; status()
|
||||
if ev.type == "model" and type(ev.ref) == "string" then
|
||||
S.model = ev.ref
|
||||
if type(ev.effort) == "string" then S.effort = ev.effort end
|
||||
status()
|
||||
elseif ev.type == "mode" and type(ev.mode) == "string" then S.mode = ev.mode; status()
|
||||
elseif ev.type == "title" and type(ev.title) == "string" then S.title = ev.title; status()
|
||||
elseif ev.type == "phase" then
|
||||
-- The main agent's phase; a subagent's (`agent`) is the tree's to show.
|
||||
if ev.agent == nil then
|
||||
S.progress = M._progress_text(ev.progress)
|
||||
local ph = type(ev.progress) == "table" and ev.progress.phase or nil
|
||||
if ph == "running_tool" then S.activity = "tools" elseif ph and S.activity ~= "writing" then S.activity = "thinking" end
|
||||
status()
|
||||
end
|
||||
elseif ev.type == "error" and type(ev.message) == "string" and ev.message:match("%S") then
|
||||
@@ -633,6 +694,12 @@ local function connect(cb, quiet)
|
||||
S.busy, S.progress = false, nil
|
||||
status()
|
||||
elseif ev.type == "usage" and type(ev.usage) == "table" and not ev.child then
|
||||
-- How much of the model's window the conversation fills, as the CLI's own bars say it.
|
||||
local total, used = tonumber(ev.context), tonumber(ev.used)
|
||||
if total and total > 0 and used and used >= 0 then
|
||||
S.ctx = math.min(100, math.max(0, math.floor(used / total * 100 + 0.5)))
|
||||
changed()
|
||||
end
|
||||
local inp = tonumber(ev.usage.input) or 0
|
||||
local outp = tonumber(ev.usage.output) or 0
|
||||
if inp > 0 or outp > 0 then
|
||||
@@ -730,11 +797,17 @@ local function ensure(cb, again)
|
||||
if not ok then return finish(false) end
|
||||
local conn = S.conn
|
||||
local meta = {}
|
||||
if M.config.mode then meta.mode = M.config.mode end
|
||||
-- The mode and the effort a session starts with: as set, else as chosen here last time. The
|
||||
-- model is the CLI's to remember (the one last used in this directory).
|
||||
local mode = M.config.mode or remembered().mode
|
||||
if mode then meta.mode = mode end
|
||||
if M.config.model then meta.model = M.config.model end
|
||||
local effort = S.effort or remembered().effort
|
||||
if effort then meta.effort = effort end
|
||||
conn:request("session/new", { cwd = S.cwd or vim.fn.getcwd(), mcpServers = {}, _meta = meta }, function(e2, r)
|
||||
if S.conn ~= conn then return finish(false) end
|
||||
if e2 or type(r) ~= "table" or type(r.sessionId) ~= "string" then
|
||||
if not_signed_in(e2) then S.signed_out = true end
|
||||
if not_signed_in(e2) and not again then
|
||||
-- This agent may have started before the person signed in: a new one is asked once
|
||||
-- before anything is said.
|
||||
@@ -755,6 +828,8 @@ local function ensure(cb, again)
|
||||
local lm = (r._meta or {}).lembas or {}
|
||||
S.mode = (r.modes and r.modes.currentModeId) or lm.mode
|
||||
S.model = lm.model
|
||||
S.effort = type(lm.effort) == "string" and lm.effort or S.effort
|
||||
S.signed_out = false
|
||||
-- A session means the sign-in works: suggestions that were refused for want of one are asked again.
|
||||
require("llembas.complete").reset()
|
||||
status()
|
||||
@@ -771,6 +846,7 @@ local function send(blocks, shown, meta)
|
||||
S.busy = true
|
||||
S.progress = nil
|
||||
S.failed = false
|
||||
S.activity = "thinking"
|
||||
status()
|
||||
ensure(function(ok)
|
||||
if not ok then S.busy = false; status(); return end
|
||||
@@ -811,9 +887,77 @@ local function editing_buf()
|
||||
if S.last_buf and vim.api.nvim_buf_is_valid(S.last_buf) then return S.last_buf end
|
||||
end
|
||||
|
||||
--- Lines of a buffer as the chip and the transcript name them: `main.rs:12-18`, or `main.rs:12`
|
||||
--- for one line reached without a selection.
|
||||
local function label(buf, first, last, point)
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
name = name ~= "" and vim.fn.fnamemodify(name, ":.") or "buffer"
|
||||
if point and first == last then return ("%s:%d"):format(name, first) end
|
||||
return ("%s:%d-%d"):format(name, first, last)
|
||||
end
|
||||
|
||||
local function set_intent(intent)
|
||||
if intent ~= "ask" and intent ~= "rewrite" and intent ~= "add" then return end
|
||||
S.intent = intent
|
||||
chat.set_intent(intent)
|
||||
end
|
||||
|
||||
local function window_of(buf)
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if vim.api.nvim_win_get_buf(w) == buf then return w end
|
||||
end
|
||||
end
|
||||
|
||||
--- What was typed with the prompt saying `rewrite ›` or `add ›`: the lines that came along are
|
||||
--- rewritten in place, or new code is written at the point — shown in the file as changes to
|
||||
--- accept or reject, never written by themselves. The focus goes to the code, where they appear.
|
||||
local function send_intent(text)
|
||||
local intent, target = S.intent, S.target
|
||||
if not target or not vim.api.nvim_buf_is_valid(target.buf) then
|
||||
local b = S.last_buf and vim.api.nvim_buf_is_valid(S.last_buf) and S.last_buf or nil
|
||||
local w = b and window_of(b)
|
||||
if not w then
|
||||
vim.notify("LLeMbas: there is no code to " .. intent .. " in — go to the file first", vim.log.levels.WARN)
|
||||
return false
|
||||
end
|
||||
local row = vim.api.nvim_win_get_cursor(w)[1]
|
||||
target = { buf = b, first = row, last = row, point = true }
|
||||
end
|
||||
local n = vim.api.nvim_buf_line_count(target.buf)
|
||||
local first, last = math.min(target.first, n), math.min(target.last, n)
|
||||
local what = label(target.buf, first, last, target.point)
|
||||
S.attached, S.attached_label, S.target = nil, nil, nil
|
||||
set_intent("ask")
|
||||
local win = window_of(target.buf)
|
||||
if not win then
|
||||
local ok, w = pcall(function() return require("llembas.layout").code_win() end)
|
||||
win = ok and w or nil
|
||||
if not win then
|
||||
vim.notify("LLeMbas: the file is no longer in a window", vim.log.levels.WARN)
|
||||
return false
|
||||
end
|
||||
vim.api.nvim_win_set_buf(win, target.buf)
|
||||
end
|
||||
chat.section("You", "LLeMbasUserHeader")
|
||||
chat.append(("[%s %s]\n%s\n"):format(intent, what, text))
|
||||
S.said = "you"
|
||||
pcall(vim.cmd, "stopinsert")
|
||||
vim.api.nvim_set_current_win(win)
|
||||
if intent == "rewrite" then
|
||||
pcall(vim.api.nvim_win_set_cursor, win, { first, 0 })
|
||||
M.edit(first, last, text)
|
||||
else
|
||||
pcall(vim.api.nvim_win_set_cursor, win, { last, 0 })
|
||||
M.generate(text)
|
||||
end
|
||||
status()
|
||||
return true
|
||||
end
|
||||
|
||||
--- A prompt typed in the panel: with what was attached, or else the name of the open file. An agent
|
||||
--- that takes the editor's context as data (`editor`) gets it so; an older one is told in a sentence.
|
||||
local function send_typed(text)
|
||||
if S.intent ~= "ask" and not text:match("^/") then return send_intent(text) end
|
||||
if S.busy then
|
||||
if S.conn and S.session and S.caps.steer then
|
||||
chat.section("You (while working)", "LLeMbasUserHeader")
|
||||
@@ -826,13 +970,17 @@ local function send_typed(text)
|
||||
vim.notify("LLeMbas is still working on the last message (:LLeMbasStop stops it)", vim.log.levels.WARN)
|
||||
return false
|
||||
end
|
||||
local attached, label = S.attached, S.attached_label
|
||||
S.attached, S.attached_label = nil, nil
|
||||
if not S.ai then
|
||||
vim.notify(OFF, vim.log.levels.INFO)
|
||||
return false
|
||||
end
|
||||
local attached, attached_label = S.attached, S.attached_label
|
||||
S.attached, S.attached_label, S.target = nil, nil, nil
|
||||
S.busy = true
|
||||
connect(function()
|
||||
local blocks, shown, meta = {}, text, nil
|
||||
if attached then
|
||||
shown = ("[%s]\n%s"):format(label, text)
|
||||
shown = ("[%s]\n%s"):format(attached_label, text)
|
||||
if S.caps.editor and attached.editor then meta = { lembas = { editor = attached.editor } }
|
||||
else vim.list_extend(blocks, attached.blocks) end
|
||||
elseif M.config.send_open_file and not text:match("^/") then
|
||||
@@ -851,20 +999,37 @@ local function send_typed(text)
|
||||
status()
|
||||
end
|
||||
|
||||
local function label(buf, first, last)
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
return ("%s:%d-%d"):format(name ~= "" and vim.fn.fnamemodify(name, ":.") or "buffer", first, last)
|
||||
local function wire()
|
||||
chat.on_send = send_typed
|
||||
chat.on_stop = M.stop
|
||||
chat.on_help = M.help
|
||||
chat.on_files = function() M.files("", false) end
|
||||
chat.on_commands = M.commands
|
||||
chat.on_intent = function() M.cycle_intent() end
|
||||
chat.on_back = function() require("llembas.layout").focus("code") end
|
||||
chat.intent = S.intent
|
||||
end
|
||||
|
||||
--- For the layout: open the panel as its right bar.
|
||||
function M._open_bar(opts)
|
||||
ui.setup_highlights()
|
||||
wire()
|
||||
chat.open(opts, false)
|
||||
status()
|
||||
end
|
||||
|
||||
function M.open(focus)
|
||||
ui.setup_highlights()
|
||||
local b = vim.api.nvim_get_current_buf()
|
||||
if vim.bo[b].buftype == "" then S.last_buf = b end
|
||||
chat.on_send = send_typed
|
||||
chat.on_stop = M.stop
|
||||
chat.on_help = M.help
|
||||
chat.on_files = function() M.files("", false) end
|
||||
chat.on_commands = M.commands
|
||||
wire()
|
||||
if bars_on() then
|
||||
-- The layout owns the right bar: it is shown (also at a width where it would fold away).
|
||||
if not chat.is_open() then require("llembas.layout").toggle("chat", true) end
|
||||
if chat.is_open() and focus ~= false then chat.focus_prompt() end
|
||||
return status()
|
||||
end
|
||||
if not S.ai then return vim.notify(OFF, vim.log.levels.INFO) end
|
||||
chat.open({
|
||||
width = M.config.width,
|
||||
position = M.config.position,
|
||||
@@ -875,9 +1040,57 @@ function M.open(focus)
|
||||
end
|
||||
|
||||
function M.toggle()
|
||||
if bars_on() then return require("llembas.layout").toggle("chat") end
|
||||
if chat.is_open() then chat.close() else M.open() end
|
||||
end
|
||||
|
||||
--- To the prompt, with what you are on: the selection, or else the cursor's line, comes along as
|
||||
--- the attachment, and the prompt says what Enter will do. `opts`: `intent` ("ask", "rewrite",
|
||||
--- "add"; nil keeps it), `first` and `last` (lines, instead of the selection or the cursor),
|
||||
--- `attach = false` (nothing comes along).
|
||||
function M.prompt(opts)
|
||||
opts = opts or {}
|
||||
if not S.ai then return vim.notify(OFF, vim.log.levels.INFO) end
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
if opts.attach ~= false and vim.bo[buf].buftype == "" then
|
||||
local first, last, point = opts.first, opts.last or opts.first, false
|
||||
if not first then
|
||||
if vim.api.nvim_get_mode().mode:match("^[vV\22]") then
|
||||
first, last = vim.fn.line("v"), vim.fn.line(".")
|
||||
if first > last then first, last = last, first end
|
||||
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "nx", false)
|
||||
else
|
||||
first = vim.api.nvim_win_get_cursor(0)[1]
|
||||
last, point = first, true
|
||||
end
|
||||
end
|
||||
S.last_buf = buf
|
||||
S.attached = { blocks = context.selection(buf, first, last), editor = context.editor(buf, first, last) }
|
||||
S.attached_label = label(buf, first, last, point)
|
||||
S.target = { buf = buf, first = first, last = last, point = point }
|
||||
end
|
||||
if opts.intent then set_intent(opts.intent) end
|
||||
M.open(true)
|
||||
status()
|
||||
end
|
||||
|
||||
--- What Enter in the prompt will do: "ask" (the question goes to the chat, with what came
|
||||
--- along), "rewrite" (the lines that came along are rewritten, shown as changes) or "add" (new
|
||||
--- code at the point, shown as changes). With a name it is set; the current one is returned.
|
||||
function M.intent(name)
|
||||
if name then
|
||||
set_intent(name)
|
||||
status()
|
||||
end
|
||||
return S.intent
|
||||
end
|
||||
|
||||
--- The next of ask, rewrite, add.
|
||||
function M.cycle_intent()
|
||||
local order = { ask = "rewrite", rewrite = "add", add = "ask" }
|
||||
return M.intent(order[S.intent] or "ask")
|
||||
end
|
||||
|
||||
--- Ask about lines `first..last` of the current buffer. With `question` it is sent at once; without,
|
||||
--- the lines are attached to the next message you type.
|
||||
function M.ask(first, last, question)
|
||||
@@ -885,6 +1098,7 @@ function M.ask(first, last, question)
|
||||
local what = label(buf, first, last)
|
||||
S.attached = { blocks = context.selection(buf, first, last), editor = context.editor(buf, first, last) }
|
||||
S.attached_label = what
|
||||
S.target = { buf = buf, first = first, last = last }
|
||||
if question and question:match("%S") then
|
||||
M.open(false)
|
||||
send_typed(question)
|
||||
@@ -994,7 +1208,8 @@ function M.new(force)
|
||||
if conn then S.last_stderr = conn:stderr() end
|
||||
S.conn, S.session, S.starting, S.connecting, S.ready, S.said = nil, nil, nil, nil, false, nil
|
||||
S.title, S.progress, S.usage, S.team, S.commands, S.caps, S.cli = nil, nil, nil, nil, {}, {}, nil
|
||||
S.attached, S.attached_label, S.shown = nil, nil, nil
|
||||
S.attached, S.attached_label, S.shown, S.target = nil, nil, nil, nil
|
||||
S.ctx, S.activity = nil, nil
|
||||
tools = {}
|
||||
pending_cards = {}
|
||||
if conn then conn:stop() end
|
||||
@@ -1020,6 +1235,7 @@ function M.mode(id)
|
||||
S.conn:request("session/set_mode", { sessionId = S.session, modeId = mode }, function(err)
|
||||
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
|
||||
S.mode = mode
|
||||
remember("mode", mode)
|
||||
status()
|
||||
end, 15000)
|
||||
end
|
||||
@@ -1280,6 +1496,7 @@ function M.model(name)
|
||||
S.conn:request("_lembas/configure", { sessionId = S.session, model = id }, function(err, r)
|
||||
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
|
||||
S.model = (r and r.model) or id
|
||||
if r and type(r.effort) == "string" then S.effort = r.effort end
|
||||
status()
|
||||
end, 30000)
|
||||
end)
|
||||
@@ -1559,11 +1776,241 @@ function M.mode_ids()
|
||||
return vim.tbl_map(function(m) return m.id end, S.modes)
|
||||
end
|
||||
|
||||
--- The mode after the current one, in the CLI's own order.
|
||||
function M.cycle_mode()
|
||||
ensure(function(ok)
|
||||
if not ok or #S.modes == 0 then return end
|
||||
local at = 0
|
||||
for i, m in ipairs(S.modes) do if m.id == S.mode then at = i end end
|
||||
M.mode(S.modes[at % #S.modes + 1].id)
|
||||
end)
|
||||
end
|
||||
|
||||
--- The effort levels there are, in the CLI's order. A model offers some of them; one it does not
|
||||
--- offer is read by the CLI as the model's own start level, and the answer says which is used.
|
||||
M.EFFORTS = { "off", "minimal", "low", "medium", "high", "xhigh", "max", "default" }
|
||||
|
||||
--- The effort of the conversation. Without a level it is picked from a list. It is remembered for
|
||||
--- this directory, and a session that starts later starts on it.
|
||||
function M.effort(level)
|
||||
if not level or level == "" then
|
||||
return vim.ui.select(M.EFFORTS, { prompt = "LLeMbas effort" .. (S.effort and (" (now: " .. S.effort .. ")") or "") },
|
||||
function(choice) if choice then M.effort(choice) end end)
|
||||
end
|
||||
if not vim.tbl_contains(M.EFFORTS, level) then
|
||||
return vim.notify("LLeMbas: an effort is one of " .. table.concat(M.EFFORTS, ", "), vim.log.levels.WARN)
|
||||
end
|
||||
remember("effort", level)
|
||||
S.effort = level
|
||||
status()
|
||||
if not (S.conn and S.session) then return end
|
||||
S.conn:request("_lembas/configure", { sessionId = S.session, effort = level }, function(err, r)
|
||||
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
|
||||
local used = r and type(r.effort) == "string" and r.effort or level
|
||||
S.effort = used
|
||||
if r and type(r.model) == "string" then S.model = r.model end
|
||||
if used ~= level then
|
||||
vim.notify(("LLeMbas: this model does not offer the effort %s; it runs on %s"):format(level, used), vim.log.levels.INFO)
|
||||
end
|
||||
status()
|
||||
end, 30000)
|
||||
end
|
||||
|
||||
--- Suggestions as you type: on, off, or (nil) the other of the two. Remembered for this directory.
|
||||
function M.autocomplete(on)
|
||||
on = require("llembas.complete").auto(on)
|
||||
remember("autocomplete", on)
|
||||
status()
|
||||
vim.notify("LLeMbas: suggestions as you type are " .. (on and "on" or "off"))
|
||||
return on
|
||||
end
|
||||
|
||||
--- LLeMbas on or off (nil: the other of the two). Off is a plain editor: the agent is stopped,
|
||||
--- no suggestion is asked for, nothing is sent, and the chat is put away. Remembered for this
|
||||
--- directory.
|
||||
function M.ai(on)
|
||||
if on == nil then on = not S.ai end
|
||||
if on == S.ai then return on end
|
||||
S.ai = on
|
||||
remember("ai", on)
|
||||
if not on then
|
||||
pcall(function() require("llembas.complete").dismiss() end)
|
||||
pcall(function() require("llembas.diff").cancel() end)
|
||||
M.restart(true)
|
||||
if not bars_on() then chat.close() end
|
||||
end
|
||||
status()
|
||||
vim.notify(on and "LLeMbas is on." or OFF, vim.log.levels.INFO)
|
||||
return on
|
||||
end
|
||||
|
||||
local function state_word()
|
||||
if not S.ai then return "off" end
|
||||
if next(pending_cards) ~= nil then return "waiting" end
|
||||
if S.busy then return S.activity or "thinking" end
|
||||
if S.starting or S.connecting or (S.conn and not S.ready) then return "starting" end
|
||||
if S.signed_out then return "signed_out" end
|
||||
if not agent_command() then return "no_cli" end
|
||||
return "idle"
|
||||
end
|
||||
|
||||
--- What holds now, for anything that shows it (a statusline, a bar): `state` ("idle",
|
||||
--- "thinking", "tools", "writing", "waiting" for your answer, "starting", "signed_out", "no_cli",
|
||||
--- "off"), `title` and `session` (whether there is one), `model`, `mode`, `effort`, `context`
|
||||
--- (percent of the model's window, or nil), `autocomplete` and `ai` (booleans), `intent`,
|
||||
--- `attachment` (the chip's text or nil), `busy`, `changes` (proposed changes in this buffer).
|
||||
--- `User LLeMbasChanged` is fired whenever one of them changes.
|
||||
function M.settings()
|
||||
local r = remembered()
|
||||
return {
|
||||
state = state_word(), title = S.title, session = S.session ~= nil,
|
||||
model = S.model, mode = S.mode or M.config.mode or r.mode, effort = S.effort or r.effort,
|
||||
context = S.ctx, autocomplete = M.config.complete.auto == true, ai = S.ai,
|
||||
intent = S.intent, attachment = S.attached_label, busy = S.busy,
|
||||
changes = require("llembas.diff").pending(),
|
||||
}
|
||||
end
|
||||
|
||||
--- The settings as lines to show: `{ id, label, value, off }` for model, mode, effort and
|
||||
--- autocomplete, in that order. `choices(id, cb)` gives what a line can be set to, `set(id,
|
||||
--- value)` sets it.
|
||||
function M.setting_lines()
|
||||
local s = M.settings()
|
||||
return {
|
||||
{ id = "model", label = "model", value = s.model and (s.model:match("[^/]+$") or s.model) or "—", off = not s.model },
|
||||
{ id = "mode", label = "mode", value = s.mode or "—", off = not s.mode },
|
||||
{ id = "effort", label = "effort", value = s.effort or "—", off = not s.effort },
|
||||
{ id = "autocomplete", label = "autocomplete", value = s.autocomplete and "on" or "off", off = not s.autocomplete },
|
||||
}
|
||||
end
|
||||
|
||||
--- What the setting `id` can be set to: `cb(list)` of `{ value, label, current }`, or
|
||||
--- `cb(nil, why)` when that cannot be said now. The models and the modes are the CLI's, asked
|
||||
--- for now; this starts the agent when it is not running.
|
||||
function M.choices(id, cb)
|
||||
if id == "autocomplete" then
|
||||
local on = M.config.complete.auto == true
|
||||
return cb({ { value = "on", label = "on", current = on }, { value = "off", label = "off", current = not on } })
|
||||
end
|
||||
if not S.ai then return cb(nil, "LLeMbas is off") end
|
||||
if id == "effort" then
|
||||
local out, now = {}, S.effort or remembered().effort
|
||||
for _, e in ipairs(M.EFFORTS) do out[#out + 1] = { value = e, label = e, current = e == now } end
|
||||
return cb(out)
|
||||
end
|
||||
if id == "mode" then
|
||||
return ensure(function(ok)
|
||||
if not ok then return cb(nil, S.signed_out and "not signed in" or (S.start_error or "the agent did not start")) end
|
||||
local out = {}
|
||||
for _, m in ipairs(S.modes) do out[#out + 1] = { value = m.id, label = m.name or m.id, current = m.id == S.mode } end
|
||||
cb(out)
|
||||
end)
|
||||
end
|
||||
if id == "model" then
|
||||
return connect(function(ok)
|
||||
if not ok then return cb(nil, S.start_error or "the agent did not start") end
|
||||
if not S.caps.editor then return cb(nil, "this LLeMbas CLI does not list models") end
|
||||
S.conn:request("_lembas/models", vim.empty_dict(), function(err, r)
|
||||
if err then return cb(nil, words(err)) end
|
||||
local out = {}
|
||||
for _, m in ipairs((r or {}).models or {}) do
|
||||
if type(m) == "table" and type(m.id) == "string" and vim.tbl_contains(m["for"] or { "main" }, "main") then
|
||||
out[#out + 1] = { value = m.id, label = (m.name and m.name ~= m.id) and m.name or (m.id:match("[^/]+$") or m.id), current = m.id == S.model }
|
||||
end
|
||||
end
|
||||
cb(out)
|
||||
end, 30000)
|
||||
end, true)
|
||||
end
|
||||
cb(nil, "there is no such setting")
|
||||
end
|
||||
|
||||
--- Set the setting `id` ("model", "mode", "effort", "autocomplete") to `value`.
|
||||
function M.set(id, value)
|
||||
if id == "model" then return M.model(value) end
|
||||
if id == "mode" then return M.mode(value) end
|
||||
if id == "effort" then return M.effort(value) end
|
||||
if id == "autocomplete" then return M.autocomplete(value == true or value == "on") end
|
||||
end
|
||||
|
||||
--- The LLeMbas menu: every command and every setting, to pick from.
|
||||
function M.menu()
|
||||
local keys = require("llembas.keys")
|
||||
local s = M.settings()
|
||||
local items = {
|
||||
{ text = "Model: " .. (s.model or "—"), run = function() M.model() end },
|
||||
{ text = "Mode: " .. (s.mode or "—"), run = function()
|
||||
M.choices("mode", function(list, why)
|
||||
if not list then return vim.notify("LLeMbas: " .. tostring(why), vim.log.levels.WARN) end
|
||||
vim.ui.select(list, { prompt = "LLeMbas mode", format_item = function(c) return c.label .. (c.current and " (now)" or "") end },
|
||||
function(c) if c then M.mode(c.value) end end)
|
||||
end)
|
||||
end },
|
||||
{ text = "Effort: " .. (s.effort or "—"), run = function() M.effort() end },
|
||||
{ text = "Autocomplete: " .. (s.autocomplete and "on" or "off"), run = function() M.autocomplete() end },
|
||||
{ text = "Autocomplete model", run = function() M.autocomplete_model() end },
|
||||
{ text = "Chat and rewrite model, saved in your account", run = function() M.main_model() end },
|
||||
{ text = "LLeMbas: " .. (s.ai and "on" or "off"), run = function() M.ai() end },
|
||||
}
|
||||
if bars_on() then
|
||||
local lay = require("llembas.layout")
|
||||
local o = lay.options()
|
||||
for _, b in ipairs({ { "top", "Top bar" }, { "bottom", "Bottom bar" }, { "tree", "Tree" }, { "chat", "Chat" } }) do
|
||||
items[#items + 1] = { text = ("%s: %s"):format(b[2], o[b[1]] and "shown" or "hidden"), run = function() lay.toggle(b[1]) end }
|
||||
end
|
||||
end
|
||||
items[#items + 1] = { text = "Make these settings the default for every directory", run = function()
|
||||
store.make_default()
|
||||
kept = nil
|
||||
vim.notify("LLeMbas: these settings are now the default; a directory with its own keeps them")
|
||||
end }
|
||||
local done = {}
|
||||
for _, k in ipairs(keys.table) do
|
||||
if k.run and not k.scope and not done[k.desc] then
|
||||
done[k.desc] = true
|
||||
items[#items + 1] = { text = k.desc, keys = keys.shown(k), run = k.run }
|
||||
end
|
||||
end
|
||||
for _, c in ipairs({ { "Compact the conversation", M.compact }, { "Show the model's thinking, on and off", M.toggle_thoughts },
|
||||
{ "Sign out", function() require("llembas.login").logout() end }, { "Stop the agent (it starts again when needed)", function() M.restart() end },
|
||||
{ "What the agent wrote on stderr", M.log } }) do
|
||||
items[#items + 1] = { text = c[1], run = c[2] }
|
||||
end
|
||||
vim.ui.select(items, {
|
||||
prompt = "LLeMbas",
|
||||
format_item = function(i) return i.keys and i.keys ~= "" and ("%s [%s]"):format(i.text, i.keys) or i.text end,
|
||||
}, function(choice) if choice then choice.run() end end)
|
||||
end
|
||||
|
||||
function M.setup(opts)
|
||||
M.config = vim.tbl_deep_extend("force", M.config, opts or {})
|
||||
if type(M.config.cmd) == "string" then M.config.cmd = { M.config.cmd, "serve", "--stdio" } end
|
||||
ui.setup_highlights()
|
||||
store.enabled = M.config.remember ~= false
|
||||
kept = nil
|
||||
-- What was switched off here before stays off; what the settings switch off is never switched on.
|
||||
local r = remembered()
|
||||
if r.ai == false then S.ai = false end
|
||||
if r.autocomplete ~= nil and M.config.complete.auto then M.config.complete.auto = r.autocomplete end
|
||||
require("llembas.complete").setup()
|
||||
local keys = M.config.keys
|
||||
if keys or M.config.bars then
|
||||
require("llembas.keys").setup(type(keys) == "table" and keys or {})
|
||||
-- Inside the LLeMbas terminal, say that this editor is in front, so that it hands its own
|
||||
-- chords through; and take that back on the way out.
|
||||
local layout = require("llembas.layout")
|
||||
layout.announce(true)
|
||||
local group = vim.api.nvim_create_augroup("llembas-terminal", { clear = true })
|
||||
vim.api.nvim_create_autocmd({ "VimLeave", "VimSuspend" }, { group = group, callback = function() layout.announce(false) end })
|
||||
vim.api.nvim_create_autocmd("VimResume", { group = group, callback = function() layout.announce(true) end })
|
||||
else
|
||||
require("llembas.keys").clear()
|
||||
end
|
||||
if M.config.bars then
|
||||
require("llembas.layout").setup(type(M.config.bars) == "table" and M.config.bars or {})
|
||||
elseif bars_on() then
|
||||
require("llembas.layout").setup(false)
|
||||
end
|
||||
end
|
||||
|
||||
--- For the plugin's other parts: the connection once the agent has started (`cb(conn | nil)`).
|
||||
@@ -1577,6 +2024,7 @@ function M._note(text, level)
|
||||
end
|
||||
|
||||
M.version = read_repo_version()
|
||||
M._status = status
|
||||
M._state = S -- for the tests
|
||||
M._words = WORDS
|
||||
M._say = words
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
-- Every key of LLeMbas, in one table. The mappings are made from it, the bottom bar shows the keys
|
||||
-- of the bar that has the focus from it, and the help and a distribution's cheat sheet read it:
|
||||
-- a key the bar shows is a key that is bound.
|
||||
--
|
||||
-- Each action has two forms. The chord is the LLeMbas terminal's (Ctrl+Shift+A …) and reaches
|
||||
-- Neovim only from a terminal that reports such keys distinctly (the kitty keyboard protocol).
|
||||
-- The other form always arrives: a key after the prefix (<Leader>l by default), or a plain key
|
||||
-- inside one of the bars. Both are bound; the bar shows the one that works.
|
||||
local M = {}
|
||||
|
||||
local function L() return require("llembas") end
|
||||
local function layout() return require("llembas.layout") end
|
||||
local function diff() return require("llembas.diff") end
|
||||
|
||||
--- { id, chord, alt, modes, scope, label, desc, run, bar }
|
||||
--- chord the chord form, or nil. alt: the form that always arrives: "<Prefix>x" (global), or a
|
||||
--- plain key (in a bar's own buffer, or global when `scope` is nil). Either may be a list.
|
||||
--- modes where `alt` is mapped when it is global (default: normal). The chord is mapped in
|
||||
--- normal, visual and insert mode.
|
||||
--- scope nil: everywhere. Otherwise the bar whose buffer has the key: "tree", "settings",
|
||||
--- "prompt", "chat" (the transcript), "change" (a buffer with proposed changes),
|
||||
--- "suggestion" (while a suggestion is shown).
|
||||
--- bar where the bottom bar shows it, with its priority there (1 first; cut from the end):
|
||||
--- { code = 1 } or { tree = { 6, "code" } } to say another word there.
|
||||
--- show how the keys are written in the bar when that is not the key's own name.
|
||||
M.table = {
|
||||
-- From the code to the chat, with what you are on.
|
||||
{ id = "ask", chord = "<C-S-A>", alt = "<Prefix>a", modes = { "n", "x" }, label = "ask",
|
||||
desc = "To the chat prompt; the selection, or else the cursor's line, comes along",
|
||||
run = function() L().prompt({ intent = "ask" }) end, bar = { code = 1, tree = 8, chat = 6 } },
|
||||
{ id = "rewrite", alt = "<Prefix>e", modes = { "n", "x" }, label = "rewrite",
|
||||
desc = "To the prompt, to have the selection or the line rewritten (shown as changes)",
|
||||
run = function() L().prompt({ intent = "rewrite" }) end },
|
||||
{ id = "add", alt = "<Prefix>g", modes = { "n", "x" }, label = "add",
|
||||
desc = "To the prompt, to have new code written at the cursor (shown as changes)",
|
||||
run = function() L().prompt({ intent = "add" }) end },
|
||||
{ id = "explain", alt = "<Prefix>x", modes = { "n", "x" }, label = "explain", range = true,
|
||||
desc = "Explain the line or the selection", run = function(first, last) L().explain(first, last) end },
|
||||
{ id = "fix", alt = "<Prefix>f", label = "fix", desc = "Fix this file's problems", run = function() L().fix() end },
|
||||
|
||||
-- Suggestions as you type.
|
||||
-- (Their keys are the plugin's settings `complete.accept` and `complete.accept_word`.)
|
||||
{ id = "suggestion_accept", alt = "<Tab>", scope = "suggestion", label = "accept suggestion", setting = "accept",
|
||||
desc = "Accept the suggestion (the grey text); without one, Neovim's own Tab", bar = { code = 2 } },
|
||||
{ id = "suggestion_word", alt = "<M-Right>", scope = "suggestion", label = "one word", setting = "accept_word",
|
||||
desc = "Accept one word of the suggestion", bar = { code = 3 } },
|
||||
{ id = "autocomplete", chord = "<C-M-a>", alt = "<Prefix>t", label = "autocomplete",
|
||||
desc = "Suggestions as you type, on and off", run = function() L().autocomplete() end },
|
||||
{ id = "autocomplete_model", chord = "<C-M-m>", alt = "<Prefix>C", label = "autocomplete model",
|
||||
desc = "Choose the model that writes suggestions", run = function() L().autocomplete_model() end },
|
||||
|
||||
-- The menu and the settings.
|
||||
{ id = "menu", chord = "<C-S-P>", alt = "<Prefix>p", label = "menu",
|
||||
desc = "The LLeMbas menu: every command and every setting", run = function() L().menu() end,
|
||||
bar = { code = 4, tree = 9, chat = 7, change = 6 } },
|
||||
{ id = "mode", chord = "<C-Tab>", alt = "<Prefix>m", label = "mode",
|
||||
desc = "Switch the mode", run = function() L().cycle_mode() end, bar = { prompt = 3 } },
|
||||
{ id = "model", chord = "<C-S-M>", alt = "<Prefix>M", label = "model",
|
||||
desc = "Choose the model", run = function() L().model() end, bar = { prompt = 4 } },
|
||||
{ id = "effort", alt = "<Prefix>E", label = "effort",
|
||||
desc = "Choose the effort", run = function() L().effort() end },
|
||||
{ id = "ai", chord = "<C-S-I>", alt = "<Prefix>I", label = "AI on/off", free = true,
|
||||
desc = "LLeMbas on and off (off: a plain editor, nothing is sent)", run = function() L().ai() end },
|
||||
{ id = "stop", chord = "<C-S-G>", alt = "<Prefix>.", label = "stop",
|
||||
desc = "Stop the running turn", run = function() L().stop() end, bar = { prompt = 6, chat = 5 } },
|
||||
|
||||
-- A proposed change.
|
||||
{ id = "accept", chord = "<C-S-Y>", alt = "ga", scope = "change", label = "accept",
|
||||
desc = "Accept the proposed change under the cursor", run = function() diff().accept(false) end, bar = { change = 1 } },
|
||||
{ id = "reject", chord = "<C-S-J>", alt = "gr", scope = "change", label = "reject",
|
||||
desc = "Reject the proposed change under the cursor", run = function() diff().reject(false) end, bar = { change = 2 } },
|
||||
{ id = "next_change", alt = "]h", scope = "change", label = "next",
|
||||
desc = "The next proposed change", run = function() diff().next_hunk() end, bar = { change = 3 } },
|
||||
{ id = "prev_change", alt = "[h", scope = "change", label = "previous",
|
||||
desc = "The previous proposed change", run = function() diff().prev_hunk() end, bar = { change = 5 } },
|
||||
{ id = "accept_all", chord = "<M-C-S-Y>", alt = "gA", scope = "change", label = "accept all",
|
||||
desc = "Accept every proposed change in the file", run = function() diff().accept(true) end, bar = { change = 4 } },
|
||||
{ id = "reject_all", alt = "gR", scope = "change", label = "reject all",
|
||||
desc = "Reject every proposed change in the file", run = function() diff().reject(true) end },
|
||||
|
||||
-- The bars.
|
||||
{ id = "tree", chord = "<C-S-E>", alt = "<Prefix>b", label = "tree", free = true,
|
||||
desc = "The file tree, show and hide", run = function() layout().toggle("tree") end, bar = { code = 6, tree = 10 } },
|
||||
{ id = "chat", chord = "<C-S-D>", alt = "<Prefix>l", label = "chat",
|
||||
desc = "The chat (the right bar), show and hide", run = function() layout().toggle("chat") end, bar = { code = 7, chat = 8 } },
|
||||
{ id = "left", alt = "<M-Left>", modes = { "n", "i" }, label = "bars", show = "Alt+←", free = true,
|
||||
desc = "To the bar on the left: chat, code, tree", run = function() layout().go(-1) end,
|
||||
bar = { chat = { 4, "code" }, settings = { 4, "code" } } },
|
||||
{ id = "right", alt = "<M-Right>", modes = { "n", "i" }, label = "bars", show = "Alt+→", free = true,
|
||||
desc = "To the bar on the right: tree, code, chat", run = function() layout().go(1) end,
|
||||
bar = { tree = { 6, "code" } } },
|
||||
{ id = "bars", alt = { "<M-Left>", "<M-Right>" }, virtual = true, label = "bars", show = "Alt+←→",
|
||||
desc = "Move between the tree, the code and the chat", bar = { code = 5 } },
|
||||
|
||||
-- Conversations.
|
||||
{ id = "sessions", alt = "<Prefix>s", label = "sessions", desc = "Earlier conversations", run = function() L().sessions() end },
|
||||
{ id = "new", alt = "<Prefix>n", label = "new", desc = "New conversation", run = function() L().new() end },
|
||||
{ id = "commands", alt = "<Prefix>c", label = "commands", desc = "Commands and skills", run = function() L().commands() end },
|
||||
{ id = "status", alt = "<Prefix>S", label = "status", free = true, desc = "Status", run = function() L().status_popup() end },
|
||||
{ id = "login", alt = "<Prefix>i", label = "sign in", free = true, desc = "Sign in", run = function() require("llembas.login").login() end },
|
||||
{ id = "help", alt = "<Prefix>?", label = "help", free = true, desc = "The plugin's commands and keys", run = function() L().help() end },
|
||||
|
||||
-- In the tree.
|
||||
{ id = "tree_open", alt = { "<CR>", "<Right>", "l" }, scope = "tree", label = "open", show = "Enter",
|
||||
desc = "Open the file; open or close the directory (→ opens, ← closes)", bar = { tree = 1 } },
|
||||
{ id = "tree_close", alt = { "<Left>", "h" }, scope = "tree", label = "close", desc = "Close the directory, or go to the one above" },
|
||||
{ id = "tree_new", alt = "a", scope = "tree", label = "new", desc = "New file, or directory with a / at the end", bar = { tree = 2 } },
|
||||
{ id = "tree_rename", alt = "r", scope = "tree", label = "rename", desc = "Rename or move", bar = { tree = 3 } },
|
||||
{ id = "tree_delete", alt = "d", scope = "tree", label = "delete", desc = "Delete, after asking (to the trash where there is one)", bar = { tree = 4 } },
|
||||
{ id = "tree_filter", alt = "/", scope = "tree", label = "filter", desc = "Filter by name as you type (empty: everything again)", bar = { tree = 5 } },
|
||||
{ id = "tree_hidden", alt = ".", scope = "tree", label = "hidden files", desc = "Hidden files, show and hide", bar = { tree = 7 } },
|
||||
{ id = "tree_refresh", alt = "R", scope = "tree", label = "refresh", desc = "Read the directory again" },
|
||||
|
||||
-- In the settings lines.
|
||||
{ id = "settings_change", alt = "<CR>", scope = "settings", label = "change", show = "Enter",
|
||||
desc = "Open the line's choices, or take the one under the cursor", bar = { settings = 1 } },
|
||||
{ id = "settings_move", alt = { "<Up>", "<Down>" }, virtual = true, scope = "settings", label = "move", show = "↑↓",
|
||||
desc = "Move between the lines and the choices", bar = { settings = 2 } },
|
||||
{ id = "settings_back", alt = "<Esc>", scope = "settings", label = "back", show = "Esc",
|
||||
desc = "Close the choices; from the lines, back to the code", bar = { settings = 3 } },
|
||||
|
||||
-- In the prompt.
|
||||
{ id = "send", alt = "<CR>", scope = "prompt", label = "send", show = "Enter",
|
||||
desc = "Send (while a turn runs: steer it)", bar = { prompt = 1 } },
|
||||
{ id = "intent", alt = "<Tab>", scope = "prompt", label = "ask/rewrite/add", show = "Tab",
|
||||
desc = "In an empty prompt: what Enter will do — ask, rewrite, add", bar = { prompt = 2 } },
|
||||
{ id = "newline", alt = "<C-j>", scope = "prompt", label = "new line", desc = "A new line in the prompt" },
|
||||
{ id = "back", alt = "<Esc>", scope = "prompt", label = "back to code", show = "Esc",
|
||||
desc = "Back to the code", bar = { prompt = 5 } },
|
||||
|
||||
-- In the transcript.
|
||||
{ id = "chat_open", alt = "<CR>", scope = "chat", label = "open file", show = "Enter",
|
||||
desc = "Open the file:line under the cursor", bar = { chat = 1 } },
|
||||
{ id = "chat_output", alt = "K", scope = "chat", label = "tool output", desc = "What the tool on this line printed", bar = { chat = 2 } },
|
||||
{ id = "chat_prompt", alt = "i", scope = "chat", label = "prompt", desc = "To the prompt", bar = { chat = 3 } },
|
||||
}
|
||||
|
||||
M.by_id = {}
|
||||
for _, k in ipairs(M.table) do M.by_id[k.id] = k end
|
||||
|
||||
local state = { set = false, prefix = "<Leader>l", guard = nil, seen = false, bound = {} }
|
||||
|
||||
local function list(v) return type(v) == "table" and v or (v and { v } or {}) end
|
||||
|
||||
--- The keys of an entry that always arrive, as a list: the table's, or the setting's it names.
|
||||
function M.alts(entry)
|
||||
if entry.setting then
|
||||
local set = (L().config.complete or {})[entry.setting]
|
||||
return (type(set) == "string" and set ~= "") and { set } or {}
|
||||
end
|
||||
return list(entry.alt)
|
||||
end
|
||||
|
||||
--- The prefix of the keys that always arrive.
|
||||
function M.prefix() return state.prefix end
|
||||
|
||||
--- `alt` of an entry as it is mapped: the prefix written out.
|
||||
function M.lhs(alt) return (alt:gsub("<Prefix>", state.prefix)) end
|
||||
|
||||
--- Where the terminal says what it is: the name the chords are remembered under.
|
||||
local function terminal_id()
|
||||
local e = vim.env
|
||||
if e.LLEMBAS_TERM or e.LLEMBAS_TTY then return "llembas" end
|
||||
if e.TMUX then return "tmux:" .. (e.TERM or "") end
|
||||
return (e.TERM_PROGRAM and e.TERM_PROGRAM ~= "" and e.TERM_PROGRAM) or e.TERM or ""
|
||||
end
|
||||
|
||||
--- Whether a terminal known to report the chords is in front: by what it says of itself.
|
||||
local function terminal_reports()
|
||||
local e = vim.env
|
||||
-- The LLeMbas terminal hands its own chords through while this editor is in front.
|
||||
if e.LLEMBAS_TERM or e.LLEMBAS_TTY then return true end
|
||||
-- A multiplexer in between takes the protocol away unless it is set up to pass it on.
|
||||
if e.TMUX or e.STY or e.ZELLIJ then return false end
|
||||
if e.KITTY_WINDOW_ID or e.GHOSTTY_RESOURCES_DIR then return true end
|
||||
local term, program = e.TERM or "", (e.TERM_PROGRAM or ""):lower()
|
||||
if term:find("kitty", 1, true) or term:find("ghostty", 1, true) or term:match("^foot") then return true end
|
||||
if program == "ghostty" or program == "rio" then return true end
|
||||
return false
|
||||
end
|
||||
|
||||
--- Whether the chords arrive, so that the bar shows them: as set (`keys.chords`), else as seen —
|
||||
--- a chord that fired in this terminal proves it, and is remembered — else as the terminal says
|
||||
--- of itself.
|
||||
function M.chords()
|
||||
local set = type(L().config.keys) == "table" and L().config.keys.chords or nil
|
||||
if set == true or set == false then return set end
|
||||
if state.seen then return true end
|
||||
if require("llembas.store").terminal(terminal_id()) then return true end
|
||||
return terminal_reports()
|
||||
end
|
||||
|
||||
--- A chord arrived: this terminal reports them.
|
||||
function M.saw_chord()
|
||||
if state.seen then return end
|
||||
state.seen = true
|
||||
pcall(function() require("llembas.store").saw_terminal(terminal_id()) end)
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
end
|
||||
|
||||
M._terminal_id, M._terminal_reports = terminal_id, terminal_reports
|
||||
function M._forget_seen() state.seen = false end
|
||||
|
||||
local NAMES = {
|
||||
["<CR>"] = "Enter", ["<Esc>"] = "Esc", ["<Tab>"] = "Tab", ["<Up>"] = "↑", ["<Down>"] = "↓",
|
||||
["<Left>"] = "←", ["<Right>"] = "→", ["<Space>"] = "Space",
|
||||
}
|
||||
|
||||
--- A key as the bar writes it: <C-S-A> is ^⇧A, <M-C-S-Y> is Alt+^⇧Y, <Leader>la is "Spc la".
|
||||
function M.written(lhs)
|
||||
lhs = M.lhs(lhs)
|
||||
if NAMES[lhs] then return NAMES[lhs] end
|
||||
local leader = vim.g.mapleader == nil and "\\" or vim.g.mapleader
|
||||
local rest = lhs:match("^<[Ll]eader>(.+)$")
|
||||
if rest then return (leader == " " and "Spc " or leader) .. rest end
|
||||
local mods, key = lhs:match("^<([CMSAD%-]-)%-?([^%-<>]+)>$")
|
||||
if mods and mods ~= "" then
|
||||
local out = ""
|
||||
if mods:find("[MA]") then out = out .. "Alt+" end
|
||||
if mods:find("C") then out = out .. "^" end
|
||||
if mods:find("S") then out = out .. "⇧" end
|
||||
key = NAMES["<" .. key .. ">"] or (#key == 1 and key:upper() or key)
|
||||
return out .. key
|
||||
end
|
||||
return lhs
|
||||
end
|
||||
|
||||
--- An entry's keys for the bar: the chord when chords arrive and it has one, else the other form.
|
||||
function M.shown(entry, chords)
|
||||
if chords == nil then chords = M.chords() end
|
||||
if chords and entry.chord then return M.written(list(entry.chord)[1]) end
|
||||
if entry.show then return entry.show end
|
||||
local alts = M.alts(entry)
|
||||
if #alts == 0 then return entry.chord and M.written(list(entry.chord)[1]) or "" end
|
||||
return M.written(alts[1])
|
||||
end
|
||||
|
||||
--- The keys the bottom bar shows where the focus is `where`, most needed first:
|
||||
--- a list of { keys, label, id }.
|
||||
function M.for_bar(where, chords)
|
||||
if chords == nil then chords = M.chords() end
|
||||
local out = {}
|
||||
for _, k in ipairs(M.table) do
|
||||
local at = k.bar and k.bar[where]
|
||||
if at then
|
||||
local prio, label = at, k.label
|
||||
if type(at) == "table" then prio, label = at[1], at[2] end
|
||||
out[#out + 1] = { keys = M.shown(k, chords), label = label, id = k.id, prio = prio }
|
||||
end
|
||||
end
|
||||
table.sort(out, function(a, b) return a.prio < b.prio end)
|
||||
return out
|
||||
end
|
||||
|
||||
--- The rows of a cheat sheet: { id, chord, alt, where, desc } with the keys as Neovim writes them.
|
||||
function M.rows()
|
||||
local out = {}
|
||||
for _, k in ipairs(M.table) do
|
||||
local alts = {}
|
||||
for _, a in ipairs(M.alts(k)) do alts[#alts + 1] = M.lhs(a) end
|
||||
out[#out + 1] = {
|
||||
id = k.id, chord = list(k.chord)[1], alt = table.concat(alts, " "),
|
||||
where = k.scope or "everywhere", desc = k.desc, modes = k.modes or { "n" },
|
||||
}
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function run(entry, by_chord)
|
||||
return function()
|
||||
if by_chord then M.saw_chord() end
|
||||
if state.guard and not entry.free and state.guard(entry) == false then return end
|
||||
if entry.range then
|
||||
-- The selection's lines, or the cursor's.
|
||||
local first, last = vim.fn.line("v"), vim.fn.line(".")
|
||||
if not vim.api.nvim_get_mode().mode:match("^[vV\22]") then first = last end
|
||||
if first > last then first, last = last, first end
|
||||
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "nx", false)
|
||||
return entry.run(first, last)
|
||||
end
|
||||
return entry.run()
|
||||
end
|
||||
end
|
||||
|
||||
--- Map the keys of the bar `scope` in its buffer, each to `handlers[id]`. The table says which
|
||||
--- keys; the bar's own module says what they do there.
|
||||
function M.bind(scope, buf, handlers, modes)
|
||||
for _, k in ipairs(M.table) do
|
||||
if k.scope == scope and not k.virtual and handlers[k.id] then
|
||||
for _, lhs in ipairs(list(k.alt)) do
|
||||
vim.keymap.set(modes and modes[k.id] or "n", lhs, handlers[k.id], { buffer = buf, nowait = true, silent = true, desc = "LLeMbas: " .. k.desc })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- The keys that are mapped everywhere: every chord, and every other form that is not a bar's own.
|
||||
--- `opts`: `{ prefix = "<Leader>l", guard = function(entry) … end }`; a guard that returns false
|
||||
--- stops the action (a distribution uses it to say what is missing).
|
||||
function M.setup(opts)
|
||||
opts = opts or {}
|
||||
M.clear()
|
||||
state.prefix = type(opts.prefix) == "string" and opts.prefix ~= "" and opts.prefix or "<Leader>l"
|
||||
state.guard = opts.guard
|
||||
state.set = true
|
||||
local function map(modes, lhs, entry, by_chord)
|
||||
vim.keymap.set(modes, lhs, run(entry, by_chord), { silent = true, desc = "LLeMbas: " .. entry.desc })
|
||||
for _, m in ipairs(list(modes)) do state.bound[#state.bound + 1] = { m, lhs } end
|
||||
end
|
||||
for _, k in ipairs(M.table) do
|
||||
if k.run then
|
||||
for _, lhs in ipairs(list(k.chord)) do map({ "n", "x", "i" }, lhs, k, true) end
|
||||
if not k.scope then
|
||||
for _, lhs in ipairs(list(k.alt)) do map(k.modes or "n", M.lhs(lhs), k, false) end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function M.clear()
|
||||
for _, b in ipairs(state.bound) do pcall(vim.keymap.del, b[1], b[2]) end
|
||||
state.bound, state.set = {}, false
|
||||
end
|
||||
|
||||
function M.is_set() return state.set end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,602 @@
|
||||
-- The four bars: the top bar (what LLeMbas is doing, the conversation, the settings), the bottom
|
||||
-- bar (the keys for where the focus is, and Neovim's own state), the tree on the left, and on the
|
||||
-- right the settings lines over the chat over the prompt. Each can be switched off; the side bars
|
||||
-- fold away by themselves when the code would get too narrow.
|
||||
--
|
||||
-- Every row is laid out from widths that are known: a cell has a fixed width, or it is the one
|
||||
-- cell that takes what is left and is cut with an ellipsis. Nothing lines up by the length of a text.
|
||||
local M = {}
|
||||
|
||||
local function L() return require("llembas") end
|
||||
local function tree() return require("llembas.tree") end
|
||||
local function chat() return require("llembas.chat") end
|
||||
local function lines() return require("llembas.lines") end
|
||||
local function keys() return require("llembas.keys") end
|
||||
local function store() return require("llembas.store") end
|
||||
|
||||
M.defaults = {
|
||||
top = true, -- the top bar (the tabline)
|
||||
bottom = true, -- the bottom bar (the statusline)
|
||||
tree = true, -- the file tree, open
|
||||
chat = true, -- the right bar, open
|
||||
tree_width = 26,
|
||||
chat_width = 42, -- kept between 34 and 50
|
||||
prompt_height = 3,
|
||||
min_code = 60, -- the side bars fold when the code would be narrower: the chat first, then the tree
|
||||
}
|
||||
|
||||
local Y = {
|
||||
on = false, prefs = vim.deepcopy(M.defaults), folded = { tree = false, chat = false }, forced = {},
|
||||
code = nil, saved = {}, shape = nil, announced = false, applying = false,
|
||||
}
|
||||
|
||||
-- ── text in cells ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
local function width_of(text) return vim.fn.strdisplaywidth(text) end
|
||||
|
||||
--- `text` in exactly `width` cells: cut with an ellipsis when longer, padded when shorter.
|
||||
function M.cell(text, width, right)
|
||||
text = (tostring(text or ""):gsub("[%c]+", " "))
|
||||
if width <= 0 then return "" end
|
||||
local w = width_of(text)
|
||||
if w > width then
|
||||
local out = ""
|
||||
for i = 0, vim.fn.strchars(text) - 1 do
|
||||
local ch = vim.fn.strcharpart(text, i, 1)
|
||||
if width_of(out .. ch) > width - 1 then break end
|
||||
out = out .. ch
|
||||
end
|
||||
text = out .. "…"
|
||||
w = width_of(text)
|
||||
end
|
||||
local pad = (" "):rep(width - w)
|
||||
return right and (pad .. text) or (text .. pad)
|
||||
end
|
||||
|
||||
--- Lay `cells` out in `width` columns. A cell is `{ text, width = n }` or `{ text, flex = true,
|
||||
--- min = n }` (one at most), with `prio` (1 stays longest; the highest number goes first when it
|
||||
--- does not fit) and `hl`. Between cells stands `sep`. Returns the cells that fit, each with its
|
||||
--- final `text`, and the row as plain text, which is exactly `width` cells wide.
|
||||
function M.fit(cells, width, sep)
|
||||
sep = sep or " │ "
|
||||
local sw = width_of(sep)
|
||||
local kept = {}
|
||||
for _, c in ipairs(cells) do kept[#kept + 1] = c end
|
||||
local function need()
|
||||
local n = 2 + math.max(#kept - 1, 0) * sw
|
||||
for _, c in ipairs(kept) do n = n + (c.flex and (c.min or 0) or c.width) end
|
||||
return n
|
||||
end
|
||||
while #kept > 1 and need() > width do
|
||||
local worst = 1
|
||||
for i, c in ipairs(kept) do if (c.prio or 1) > (kept[worst].prio or 1) then worst = i end end
|
||||
table.remove(kept, worst)
|
||||
end
|
||||
local left = width - need()
|
||||
local out, plain = {}, " "
|
||||
for i, c in ipairs(kept) do
|
||||
local w = c.flex and ((c.min or 0) + math.max(left, 0)) or c.width
|
||||
if not c.flex and #kept == 1 then w = math.min(w, math.max(width - 2, 0)) end
|
||||
local text = M.cell(c.text, w, c.right)
|
||||
out[#out + 1] = { text = text, hl = c.hl, id = c.id }
|
||||
plain = plain .. text .. (i < #kept and sep or "")
|
||||
end
|
||||
-- No flexible cell among those kept: what is left stays empty at the end.
|
||||
plain = M.cell(plain .. " ", width)
|
||||
return out, plain
|
||||
end
|
||||
|
||||
local function esc(text) return (text:gsub("%%", "%%%%")) end
|
||||
|
||||
local function line_of(cells, width, sep, sep_hl, base_hl)
|
||||
local parts = { "%#" .. base_hl .. "# " }
|
||||
for i, c in ipairs(cells) do
|
||||
parts[#parts + 1] = "%#" .. (c.hl or base_hl) .. "#" .. esc(c.text)
|
||||
if i < #cells then parts[#parts + 1] = "%#" .. sep_hl .. "#" .. esc(sep) end
|
||||
end
|
||||
parts[#parts + 1] = "%#" .. base_hl .. "#"
|
||||
local used = 1
|
||||
for i, c in ipairs(cells) do used = used + width_of(c.text) + (i < #cells and width_of(sep) or 0) end
|
||||
parts[#parts + 1] = (" "):rep(math.max(width - used, 0))
|
||||
return table.concat(parts)
|
||||
end
|
||||
|
||||
-- ── the top bar ────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
local STATE = {
|
||||
idle = { "idle", "idle", "LLeMbasBarIdle" },
|
||||
thinking = { "thinking", "think", "LLeMbasBarBusy" },
|
||||
tools = { "tools", "tools", "LLeMbasBarBusy" },
|
||||
writing = { "writing", "write", "LLeMbasBarBusy" },
|
||||
waiting = { "waiting for you", "waiting", "LLeMbasBarWaiting" },
|
||||
starting = { "starting", "start", "LLeMbasBarBusy" },
|
||||
signed_out = { "not signed in", "sign in", "LLeMbasBarOff" },
|
||||
no_cli = { "no CLI", "no CLI", "LLeMbasBarOff" },
|
||||
off = { "AI off", "AI off", "LLeMbasBarOff" },
|
||||
}
|
||||
M.STATE_WIDTH, M.STATE_WIDTH_NARROW = 17, 9
|
||||
|
||||
local function short_model(ref)
|
||||
if type(ref) ~= "string" or ref == "" then return "—" end
|
||||
return ref:match("[^/]+$") or ref
|
||||
end
|
||||
|
||||
local function diagnostics()
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
local ok, count = pcall(vim.diagnostic.count, buf)
|
||||
if not ok or type(count) ~= "table" then return "" end
|
||||
local e, w = count[vim.diagnostic.severity.ERROR] or 0, count[vim.diagnostic.severity.WARN] or 0
|
||||
if e == 0 and w == 0 then return "" end
|
||||
return ("E%d W%d"):format(math.min(e, 99), math.min(w, 99))
|
||||
end
|
||||
|
||||
local function branch()
|
||||
local b = tree().branch()
|
||||
if b and b ~= "" then return b end
|
||||
local s = vim.b.minigit_summary
|
||||
if type(s) == "table" and type(s.head_name) == "string" then return s.head_name end
|
||||
return type(vim.b.gitsigns_head) == "string" and vim.b.gitsigns_head or ""
|
||||
end
|
||||
|
||||
--- The cells of the top bar for `width` columns.
|
||||
function M.top_cells(width)
|
||||
local s = L().settings()
|
||||
local narrow = width < 100
|
||||
local st = STATE[s.state] or STATE.idle
|
||||
local busy = s.state == "thinking" or s.state == "tools" or s.state == "writing" or s.state == "starting"
|
||||
local sw = narrow and M.STATE_WIDTH_NARROW or M.STATE_WIDTH
|
||||
local model_room = narrow and 10 or 16
|
||||
local rest = " · " .. (s.mode or "—") .. " · " .. (s.effort or "—")
|
||||
local model = short_model(s.model)
|
||||
if width_of(model) > model_room then model = M.cell(model, model_room) end
|
||||
local cells = {
|
||||
{ id = "state", text = (busy and "◐ " or "● ") .. (narrow and st[2] or st[1]), width = sw, prio = 1, hl = st[3] },
|
||||
{ id = "title", text = (s.title and s.title ~= "") and s.title or (s.session and "conversation" or "no conversation yet"),
|
||||
flex = true, min = 8, prio = 3, hl = "LLeMbasBarTitle" },
|
||||
{ id = "settings", text = model .. rest, width = model_room + 16, prio = 2, hl = "LLeMbasBar" },
|
||||
{ id = "context", text = s.context and ("ctx %d%%"):format(s.context) or "ctx —", width = 8, prio = 5, hl = "LLeMbasBar" },
|
||||
{ id = "autocomplete", text = "AC " .. (s.autocomplete and "on" or "off"), width = 6, prio = 4,
|
||||
hl = s.autocomplete and "LLeMbasBar" or "LLeMbasBarOff" },
|
||||
}
|
||||
local b, d = branch(), diagnostics()
|
||||
if b ~= "" then cells[#cells + 1] = { id = "branch", text = b, width = 14, prio = 7, hl = "LLeMbasBarFact" } end
|
||||
if d ~= "" then cells[#cells + 1] = { id = "problems", text = d, width = 7, prio = 6, hl = "LLeMbasBarFact" } end
|
||||
return cells
|
||||
end
|
||||
|
||||
--- The top bar as plain text, exactly `width` cells (the screen's width when not given).
|
||||
function M.top_text(width)
|
||||
width = width or vim.o.columns
|
||||
local _, plain = M.fit(M.top_cells(width), width)
|
||||
return plain
|
||||
end
|
||||
|
||||
--- 'tabline'.
|
||||
function M.top()
|
||||
local ok, out = pcall(function()
|
||||
local width = vim.o.columns
|
||||
local cells = M.fit(M.top_cells(width), width)
|
||||
return line_of(cells, width, " │ ", "LLeMbasBarSeparator", "LLeMbasBar")
|
||||
end)
|
||||
return ok and out or ""
|
||||
end
|
||||
|
||||
-- ── the bottom bar ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
local MODES = {
|
||||
n = "NOR", no = "O-P", i = "INS", ic = "INS", ix = "INS", v = "VIS", V = "V-L", ["\22"] = "V-B",
|
||||
s = "SEL", S = "S-L", ["\19"] = "S-B", R = "REP", Rv = "REP", c = "CMD", cv = "CMD", t = "TER", nt = "NOR",
|
||||
r = "ASK", rm = "ASK", ["r?"] = "ASK", ["!"] = "RUN",
|
||||
}
|
||||
|
||||
local function mode_word()
|
||||
local m = vim.api.nvim_get_mode().mode
|
||||
return MODES[m] or MODES[m:sub(1, 2)] or MODES[m:sub(1, 1)] or "???"
|
||||
end
|
||||
|
||||
local function search_count()
|
||||
if vim.v.hlsearch ~= 1 then return "" end
|
||||
local ok, c = pcall(vim.fn.searchcount, { maxcount = 999, timeout = 30 })
|
||||
if not ok or type(c) ~= "table" or (c.total or 0) == 0 then return "" end
|
||||
if c.incomplete == 1 then return "?/?" end
|
||||
return ("%d/%s"):format(c.current or 0, c.incomplete == 2 and "999+" or tostring(c.total))
|
||||
end
|
||||
|
||||
--- Where the focus is, as the bottom bar and the keys name it: "tree", "settings", "chat" (the
|
||||
--- transcript), "prompt", "change" (code with proposed changes) or "code".
|
||||
function M.where(win)
|
||||
win = win or vim.api.nvim_get_current_win()
|
||||
if not vim.api.nvim_win_is_valid(win) then return "code" end
|
||||
local buf = vim.api.nvim_win_get_buf(win)
|
||||
if buf == tree().buf() then return "tree" end
|
||||
if buf == lines().buf() then return "settings" end
|
||||
if buf == chat().tbuf then return "chat" end
|
||||
if buf == chat().ibuf then return "prompt" end
|
||||
if require("llembas.diff").pending(buf) > 0 then return "change" end
|
||||
return "code"
|
||||
end
|
||||
|
||||
--- Neovim's own state, in cells of fixed width: the mode, the modified flag, the macro being
|
||||
--- recorded, the search count, the cursor's line and column, and last the pending operator.
|
||||
--- `%l`, `%v` and `%S` are the statusline's own items, so they are as live as Neovim's. `%S` is
|
||||
--- the one item whose width Neovim decides (an empty one takes no cell at all), so it stands at
|
||||
--- the very end, in the five cells kept for it, where it moves nothing else.
|
||||
local function vim_segment(width)
|
||||
local rec = vim.fn.reg_recording()
|
||||
local mode = mode_word()
|
||||
local modified = vim.bo.modified and "+" or " "
|
||||
local macro = rec ~= "" and ("@" .. rec) or " "
|
||||
if width < 60 then return 15, (" %s %%5l:%%-3v "):format(mode), (" %s "):format(mode) end
|
||||
if width < 120 then
|
||||
return 20, (" %s %s %s %%5l:%%-3v "):format(mode, modified, macro), (" %s %s %s "):format(mode, modified, macro)
|
||||
end
|
||||
local search = M.cell(search_count(), 8, true)
|
||||
return 35, (" %s %s %s %s %%5l:%%-3v %%<%%.5S"):format(mode, modified, macro, esc(search)),
|
||||
(" %s %s %s %s "):format(mode, modified, macro, search)
|
||||
end
|
||||
|
||||
--- The keys of the bottom bar for the focus `where`, cut to `room` cells by priority: a list of
|
||||
--- { keys, label } and the text.
|
||||
function M.bottom_keys(where, room, chords)
|
||||
local list = keys().for_bar(where, chords)
|
||||
local function text_of(items)
|
||||
local parts = {}
|
||||
for _, k in ipairs(items) do parts[#parts + 1] = k.keys .. " " .. k.label end
|
||||
return " " .. table.concat(parts, " · ")
|
||||
end
|
||||
while #list > 0 and width_of(text_of(list)) > room do table.remove(list) end
|
||||
return list, #list > 0 and text_of(list) or ""
|
||||
end
|
||||
|
||||
--- The bottom bar's keys as plain text for the focus `where` (now, when not given), cut to the
|
||||
--- screen's width less Neovim's own segment.
|
||||
function M.bottom_text(where, width, chords)
|
||||
width = width or vim.o.columns
|
||||
local seg = vim_segment(width)
|
||||
local _, text = M.bottom_keys(where or M.where(), width - seg, chords)
|
||||
return text
|
||||
end
|
||||
|
||||
--- 'statusline'.
|
||||
function M.bottom()
|
||||
local ok, out = pcall(function()
|
||||
local width = vim.o.columns
|
||||
local seg, items = vim_segment(width)
|
||||
local room = width - seg
|
||||
local list = M.bottom_keys(M.where(), room)
|
||||
local parts, used = { "%#LLeMbasBar# " }, 1
|
||||
for i, k in ipairs(list) do
|
||||
local tail = " " .. k.label .. (i < #list and " · " or "")
|
||||
parts[#parts + 1] = "%#LLeMbasBarKey#" .. esc(k.keys) .. "%#LLeMbasBar#" .. esc(tail)
|
||||
used = used + width_of(k.keys) + width_of(tail)
|
||||
end
|
||||
parts[#parts + 1] = (" "):rep(math.max(room - used, 0))
|
||||
parts[#parts + 1] = "%#LLeMbasBarVim#" .. items
|
||||
return table.concat(parts)
|
||||
end)
|
||||
return ok and out or ""
|
||||
end
|
||||
|
||||
-- ── the windows ────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
local function is_bar(win)
|
||||
local buf = vim.api.nvim_win_get_buf(win)
|
||||
return buf == tree().buf() or buf == lines().buf() or buf == chat().tbuf or buf == chat().ibuf
|
||||
end
|
||||
|
||||
local function floating(win) return vim.api.nvim_win_get_config(win).relative ~= "" end
|
||||
|
||||
--- The window the code is in: the last one that had the focus and is not a bar.
|
||||
function M.code_win()
|
||||
if Y.code and vim.api.nvim_win_is_valid(Y.code) and not is_bar(Y.code) and not floating(Y.code)
|
||||
and vim.api.nvim_win_get_tabpage(Y.code) == vim.api.nvim_get_current_tabpage() then
|
||||
return Y.code
|
||||
end
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if not is_bar(w) and not floating(w) then
|
||||
Y.code = w
|
||||
return w
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function clamp(n, lo, hi) return math.max(lo, math.min(hi, n)) end
|
||||
|
||||
--- Which side bars are shown at this size: what is wanted, less what does not leave the code
|
||||
--- `min_code` columns — the chat goes first, then the tree. Returns { tree, chat } and the
|
||||
--- widths. A bar the person opened by hand at this size stays.
|
||||
function M.plan(columns, rows)
|
||||
columns, rows = columns or vim.o.columns, rows or vim.o.lines
|
||||
local p = Y.prefs
|
||||
local tw, cw = clamp(p.tree_width, 16, 60), clamp(p.chat_width, 34, 50)
|
||||
local ai = L().settings().ai
|
||||
local want = { tree = p.tree, chat = p.chat and ai }
|
||||
local function code(t, c) return columns - (t and (tw + 1) or 0) - (c and (cw + 1) or 0) end
|
||||
local folded = { tree = false, chat = false }
|
||||
if want.chat and not Y.forced.chat and code(want.tree, true) < p.min_code then folded.chat = true end
|
||||
local chat_on = want.chat and not folded.chat
|
||||
if want.tree and not Y.forced.tree and code(true, chat_on) < p.min_code then folded.tree = true end
|
||||
local tree_on = want.tree and not folded.tree
|
||||
-- A screen too low for a chat with its prompt: the chat goes.
|
||||
if chat_on and rows < 10 and not Y.forced.chat then chat_on, folded.chat = false, true end
|
||||
return { tree = tree_on, chat = chat_on, folded = folded, tree_width = tw, chat_width = cw,
|
||||
lines = rows >= 18, prompt_height = rows >= 18 and p.prompt_height or 1 }
|
||||
end
|
||||
|
||||
--- Open and close the side bars as `plan` says.
|
||||
function M.apply()
|
||||
if not Y.on or Y.applying then return end
|
||||
Y.applying = true
|
||||
local ok, err = pcall(function()
|
||||
local plan = M.plan()
|
||||
Y.folded = plan.folded
|
||||
M.code_win()
|
||||
if plan.tree then
|
||||
local w = tree().open(plan.tree_width)
|
||||
if w and vim.api.nvim_win_get_width(w) ~= plan.tree_width then
|
||||
pcall(vim.api.nvim_win_set_width, w, plan.tree_width)
|
||||
end
|
||||
else
|
||||
tree().close()
|
||||
end
|
||||
local shape = ("%s:%d:%d"):format(tostring(plan.lines), plan.prompt_height, plan.chat_width)
|
||||
if plan.chat then
|
||||
if chat().is_open() and Y.shape ~= shape then chat().close() end
|
||||
if not chat().is_open() then
|
||||
Y.shape = shape
|
||||
L()._open_bar({
|
||||
width = plan.chat_width, position = "right", prompt_height = plan.prompt_height,
|
||||
bars = true, lines = plan.lines,
|
||||
})
|
||||
end
|
||||
elseif chat().is_open() then
|
||||
chat().close()
|
||||
end
|
||||
end)
|
||||
Y.applying = false
|
||||
if not ok then vim.schedule(function() vim.notify("LLeMbas: the bars could not be laid out: " .. tostring(err), vim.log.levels.WARN) end) end
|
||||
pcall(vim.cmd, "redrawtabline")
|
||||
pcall(vim.cmd, "redrawstatus")
|
||||
end
|
||||
|
||||
--- Whether a side bar is on the screen now.
|
||||
function M.shown(which)
|
||||
if which == "tree" then return tree().is_open() end
|
||||
if which == "chat" then return chat().is_open() end
|
||||
return Y.prefs[which] == true
|
||||
end
|
||||
|
||||
local function remember(key, value) pcall(function() store().set(key, value) end) end
|
||||
|
||||
--- Show or hide a bar: "tree", "chat", "top", "bottom". `on` nil: the other of the two. A side
|
||||
--- bar asked for at a width where it would be folded away is shown all the same.
|
||||
function M.toggle(which, on)
|
||||
if which ~= "tree" and which ~= "chat" and which ~= "top" and which ~= "bottom" then return end
|
||||
if not Y.on then
|
||||
if which == "chat" then return L().toggle() end
|
||||
if which == "tree" then
|
||||
if tree().is_open() then tree().close() else tree().open(Y.prefs.tree_width) end
|
||||
end
|
||||
return
|
||||
end
|
||||
if which == "top" or which == "bottom" then
|
||||
if on == nil then on = not Y.prefs[which] end
|
||||
Y.prefs[which] = on
|
||||
remember(which, on)
|
||||
return M.bars()
|
||||
end
|
||||
local is = M.shown(which)
|
||||
if on == nil then on = not is end
|
||||
Y.prefs[which] = on
|
||||
Y.forced[which] = on and true or nil
|
||||
remember(which, on)
|
||||
if which == "chat" and on and not L().settings().ai then
|
||||
return vim.notify("LLeMbas is off (" .. keys().shown(keys().by_id.ai) .. " turns it on)", vim.log.levels.INFO)
|
||||
end
|
||||
M.apply()
|
||||
end
|
||||
|
||||
--- Put the focus in a bar: "tree", "code" or "chat" (the prompt). A side bar that is hidden is shown.
|
||||
function M.focus(which)
|
||||
if which == "tree" then
|
||||
if not tree().is_open() then M.toggle("tree", true) end
|
||||
local w = tree().win()
|
||||
if w then
|
||||
vim.cmd("stopinsert")
|
||||
vim.api.nvim_set_current_win(w)
|
||||
end
|
||||
elseif which == "chat" then
|
||||
if not L().settings().ai then
|
||||
return vim.notify("LLeMbas is off (" .. keys().shown(keys().by_id.ai) .. " turns it on)", vim.log.levels.INFO)
|
||||
end
|
||||
if not chat().is_open() then
|
||||
if Y.on then M.toggle("chat", true) else L().open(true) end
|
||||
end
|
||||
chat().focus_prompt()
|
||||
else
|
||||
local w = M.code_win()
|
||||
if w then
|
||||
vim.cmd("stopinsert")
|
||||
vim.api.nvim_set_current_win(w)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local ORDER = { "tree", "code", "chat" }
|
||||
|
||||
--- Move the focus one bar to the left (-1) or to the right (1): tree, code, chat.
|
||||
function M.go(step)
|
||||
local where = M.where()
|
||||
local at = (where == "tree" and 1) or ((where == "code" or where == "change") and 2) or 3
|
||||
local to = clamp(at + step, 1, 3)
|
||||
if to == at then return end
|
||||
M.focus(ORDER[to])
|
||||
end
|
||||
|
||||
-- ── the terminal ───────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
--- The bytes that set the terminal's user var `llembas_ide` to `value` ("" clears it): iTerm2's
|
||||
--- OSC 1337 SetUserVar, which WezTerm and the LLeMbas terminal read. Inside tmux it is wrapped
|
||||
--- so that tmux passes it on.
|
||||
function M.uservar_bytes(value, tmux)
|
||||
local seq = "\27]1337;SetUserVar=llembas_ide=" .. vim.base64.encode(value or "") .. "\7"
|
||||
if tmux then seq = "\27Ptmux;" .. seq:gsub("\27", "\27\27") .. "\27\\" end
|
||||
return seq
|
||||
end
|
||||
|
||||
local function in_llembas_terminal()
|
||||
local e = vim.env
|
||||
return (e.LLEMBAS_TERM ~= nil and e.LLEMBAS_TERM ~= "") or (e.LLEMBAS_TTY ~= nil and e.LLEMBAS_TTY ~= "")
|
||||
end
|
||||
|
||||
--- Tell the LLeMbas terminal that this editor is the program in front (`on`), or no longer is:
|
||||
--- it hands its own chords (Ctrl+Shift+A …) through to the program that says `llembas_ide=1`.
|
||||
--- Written only inside that terminal (`$LLEMBAS_TERM` or `$LLEMBAS_TTY`), and nowhere else.
|
||||
function M.announce(on)
|
||||
if not in_llembas_terminal() then return false end
|
||||
if on == Y.announced then return true end
|
||||
Y.announced = on
|
||||
-- Standard error is the terminal itself, whatever Neovim draws with (as Neovim's own OSC 52 does).
|
||||
pcall(vim.api.nvim_chan_send, 2, M.uservar_bytes(on and "1" or "", vim.env.TMUX ~= nil and vim.env.TMUX ~= ""))
|
||||
return true
|
||||
end
|
||||
|
||||
-- ── setting up ─────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
--- Put the top and the bottom bar where the settings say, and give back what was there when one
|
||||
--- is switched off.
|
||||
function M.bars()
|
||||
local p = Y.prefs
|
||||
if Y.on and p.top then
|
||||
if not Y.saved.tabline then Y.saved.tabline = { vim.o.tabline, vim.o.showtabline } end
|
||||
vim.o.tabline = "%!v:lua.require'llembas.layout'.top()"
|
||||
vim.o.showtabline = 2
|
||||
elseif Y.saved.tabline then
|
||||
vim.o.tabline, vim.o.showtabline = Y.saved.tabline[1], Y.saved.tabline[2]
|
||||
Y.saved.tabline = nil
|
||||
end
|
||||
if Y.on and p.bottom then
|
||||
if not Y.saved.statusline then Y.saved.statusline = { vim.o.statusline, vim.o.laststatus, vim.o.showcmdloc } end
|
||||
vim.o.statusline = "%!v:lua.require'llembas.layout'.bottom()"
|
||||
vim.o.laststatus = 3
|
||||
vim.o.showcmdloc = "statusline" -- the pending operator is the bar's %S
|
||||
elseif Y.saved.statusline then
|
||||
vim.o.statusline, vim.o.laststatus, vim.o.showcmdloc = Y.saved.statusline[1], Y.saved.statusline[2], Y.saved.statusline[3]
|
||||
Y.saved.statusline = nil
|
||||
end
|
||||
pcall(vim.cmd, "redrawtabline")
|
||||
pcall(vim.cmd, "redrawstatus")
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasBars", modeline = false })
|
||||
end
|
||||
|
||||
--- What the layout is set to now (a copy), with what is folded away at this size.
|
||||
function M.options()
|
||||
local out = vim.deepcopy(Y.prefs)
|
||||
out.on, out.folded = Y.on, vim.deepcopy(Y.folded)
|
||||
return out
|
||||
end
|
||||
|
||||
local function widths_changed()
|
||||
if not Y.on then return end
|
||||
local tw, cw = tree().win(), chat().is_open() and vim.fn.bufwinid(chat().tbuf) or -1
|
||||
if tw and not Y.folded.tree then
|
||||
local w = vim.api.nvim_win_get_width(tw)
|
||||
if w ~= Y.prefs.tree_width and w >= 16 and w <= 60 then
|
||||
Y.prefs.tree_width = w
|
||||
tree().width = w
|
||||
remember("tree_width", w)
|
||||
end
|
||||
end
|
||||
if cw and cw ~= -1 and not Y.folded.chat then
|
||||
local w = vim.api.nvim_win_get_width(cw)
|
||||
if w ~= Y.prefs.chat_width and w >= 34 and w <= 50 then
|
||||
Y.prefs.chat_width = w
|
||||
remember("chat_width", w)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Remember the side bars' widths as they are now (also done when Neovim sees a window resized,
|
||||
--- and on the way out).
|
||||
function M.remember_widths() widths_changed() end
|
||||
|
||||
--- Close the side bars, for something that must see only the code's windows (saving a session);
|
||||
--- `M.apply()` brings them back.
|
||||
function M.hide()
|
||||
tree().close()
|
||||
chat().close()
|
||||
end
|
||||
|
||||
--- Turn the layout on with `opts` (see `M.defaults`; `false` turns it off). `opts` are what a
|
||||
--- directory starts with. What the person then changed by hand there — which bars are shown, how
|
||||
--- wide the side bars are — is remembered for that directory and holds the next time.
|
||||
function M.setup(opts)
|
||||
if opts == false then
|
||||
Y.on = false
|
||||
pcall(vim.api.nvim_del_augroup_by_name, "llembas-layout")
|
||||
M.bars()
|
||||
return
|
||||
end
|
||||
Y.given = vim.tbl_extend("force", Y.given or {}, type(opts) == "table" and opts or {})
|
||||
local prefs = vim.tbl_extend("force", vim.deepcopy(M.defaults), Y.given)
|
||||
local remembered = store().get()
|
||||
for _, k in ipairs({ "top", "bottom", "tree", "chat", "tree_width", "chat_width" }) do
|
||||
if remembered[k] ~= nil then prefs[k] = remembered[k] end
|
||||
end
|
||||
Y.prefs = prefs
|
||||
Y.on = true
|
||||
require("llembas.ui").setup_highlights()
|
||||
M.bars()
|
||||
|
||||
local group = vim.api.nvim_create_augroup("llembas-layout", { clear = true })
|
||||
local function redraw()
|
||||
pcall(vim.cmd, "redrawtabline")
|
||||
pcall(vim.cmd, "redrawstatus")
|
||||
end
|
||||
vim.api.nvim_create_autocmd("User", { group = group, pattern = "LLeMbasChanged", callback = function()
|
||||
-- AI switched on or off changes what is laid out.
|
||||
local ai = L().settings().ai
|
||||
if Y.ai ~= ai then
|
||||
Y.ai = ai
|
||||
vim.schedule(M.apply)
|
||||
end
|
||||
redraw()
|
||||
end })
|
||||
vim.api.nvim_create_autocmd({ "WinEnter", "BufEnter", "ModeChanged", "DiagnosticChanged", "RecordingEnter", "RecordingLeave" },
|
||||
{ group = group, callback = function()
|
||||
local w = vim.api.nvim_get_current_win()
|
||||
if not is_bar(w) and not floating(w) then Y.code = w end
|
||||
vim.schedule(redraw)
|
||||
end })
|
||||
vim.api.nvim_create_autocmd("VimResized", { group = group, callback = function()
|
||||
-- A new size is judged anew: what was opened by hand at the old one no longer holds.
|
||||
Y.forced = {}
|
||||
vim.schedule(M.apply)
|
||||
end })
|
||||
vim.api.nvim_create_autocmd({ "WinResized", "VimLeavePre" }, { group = group, callback = function()
|
||||
if not Y.applying then widths_changed() end
|
||||
end })
|
||||
vim.api.nvim_create_autocmd("QuitPre", { group = group, callback = function()
|
||||
-- Leaving the last window of code leaves the editor: the bars do not keep it open.
|
||||
local cur = vim.api.nvim_get_current_win()
|
||||
if is_bar(cur) or floating(cur) then return end
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if w ~= cur and not is_bar(w) and not floating(w) then return end
|
||||
end
|
||||
if #vim.api.nvim_list_tabpages() > 1 then return end
|
||||
Y.applying = true
|
||||
M.hide()
|
||||
Y.applying = false
|
||||
end })
|
||||
Y.ai = L().settings().ai
|
||||
if vim.v.vim_did_enter == 1 then
|
||||
M.apply()
|
||||
else
|
||||
vim.api.nvim_create_autocmd("VimEnter", { group = group, once = true, callback = function() vim.schedule(M.apply) end })
|
||||
end
|
||||
end
|
||||
|
||||
M._state = Y
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,161 @@
|
||||
-- The settings lines: what holds now — model, mode, effort, autocomplete — one line each, at the
|
||||
-- top of the right bar. Enter on a line opens its choices right under it, in the bar; Enter on a
|
||||
-- choice takes it. The values and the choices are the plugin's public ones (`setting_lines`,
|
||||
-- `choices`, `set`): this module only draws them.
|
||||
local M = {}
|
||||
local ns = vim.api.nvim_create_namespace("llembas-lines")
|
||||
|
||||
local P = { buf = nil, open = nil, choices = nil, note = nil, rows = {} }
|
||||
M.LABEL_WIDTH = 14 -- every label is cut or padded to this, so the values share one edge
|
||||
M.MAX_CHOICES = 8 -- rows the bar gives a list of choices before it scrolls
|
||||
|
||||
local function L() return require("llembas") end
|
||||
local function valid() return P.buf and vim.api.nvim_buf_is_valid(P.buf) end
|
||||
|
||||
function M.win()
|
||||
if not valid() then return nil end
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if vim.api.nvim_win_get_buf(w) == P.buf then return w end
|
||||
end
|
||||
end
|
||||
|
||||
local function one_line(text) return (tostring(text or ""):gsub("[%c]+", " ")) end
|
||||
|
||||
--- How many rows the lines want now: the settings, and the open list up to its limit.
|
||||
function M.height()
|
||||
local settings = #L().setting_lines()
|
||||
if not P.open then return settings end
|
||||
local extra = P.choices and #P.choices or 1
|
||||
return settings + math.min(math.max(extra, 1), M.MAX_CHOICES)
|
||||
end
|
||||
|
||||
function M.render()
|
||||
if not valid() then return end
|
||||
local lines, rows, marks = {}, {}, {}
|
||||
for _, s in ipairs(L().setting_lines()) do
|
||||
local label = vim.fn.strcharpart(s.label, 0, M.LABEL_WIDTH - 1)
|
||||
lines[#lines + 1] = label .. (" "):rep(M.LABEL_WIDTH - vim.fn.strdisplaywidth(label)) .. one_line(s.value)
|
||||
rows[#rows + 1] = { kind = "setting", id = s.id }
|
||||
marks[#marks + 1] = { #lines - 1, 0, #label, "LLeMbasLineLabel" }
|
||||
marks[#marks + 1] = { #lines - 1, M.LABEL_WIDTH, #lines[#lines], s.off and "LLeMbasLineOff" or "LLeMbasLineValue" }
|
||||
if P.open == s.id then
|
||||
if P.choices then
|
||||
for _, c in ipairs(P.choices) do
|
||||
lines[#lines + 1] = (c.current and " ● " or " ○ ") .. one_line(c.label)
|
||||
rows[#rows + 1] = { kind = "choice", id = s.id, value = c.value }
|
||||
if c.current then marks[#marks + 1] = { #lines - 1, 0, #lines[#lines], "LLeMbasLineCurrent" } end
|
||||
end
|
||||
if #P.choices == 0 then
|
||||
lines[#lines + 1] = " (nothing to choose from)"
|
||||
rows[#rows + 1] = { kind = "note" }
|
||||
end
|
||||
else
|
||||
lines[#lines + 1] = " " .. one_line(P.note or "…")
|
||||
rows[#rows + 1] = { kind = "note" }
|
||||
marks[#marks + 1] = { #lines - 1, 0, #lines[#lines], "LLeMbasNote" }
|
||||
end
|
||||
end
|
||||
end
|
||||
P.rows = rows
|
||||
vim.bo[P.buf].modifiable = true
|
||||
vim.api.nvim_buf_set_lines(P.buf, 0, -1, false, lines)
|
||||
vim.bo[P.buf].modifiable = false
|
||||
vim.api.nvim_buf_clear_namespace(P.buf, ns, 0, -1)
|
||||
for _, m in ipairs(marks) do
|
||||
pcall(vim.api.nvim_buf_set_extmark, P.buf, ns, m[1], m[2], { end_col = m[3], hl_group = m[4] })
|
||||
end
|
||||
local win = M.win()
|
||||
if win then pcall(vim.api.nvim_win_set_height, win, M.height()) end
|
||||
end
|
||||
|
||||
local function row_here()
|
||||
local win = M.win()
|
||||
if not win then return nil end
|
||||
return P.rows[vim.api.nvim_win_get_cursor(win)[1]], win
|
||||
end
|
||||
|
||||
local function cursor_to(pred)
|
||||
local win = M.win()
|
||||
if not win then return end
|
||||
for i, r in ipairs(P.rows) do
|
||||
if pred(r) then return pcall(vim.api.nvim_win_set_cursor, win, { i, 0 }) end
|
||||
end
|
||||
end
|
||||
|
||||
--- Close the open list. True when one was open.
|
||||
function M.close_choices()
|
||||
if not P.open then return false end
|
||||
local id = P.open
|
||||
P.open, P.choices, P.note = nil, nil, nil
|
||||
M.render()
|
||||
cursor_to(function(r) return r.kind == "setting" and r.id == id end)
|
||||
return true
|
||||
end
|
||||
|
||||
--- Open the choices of the setting `id` under its line.
|
||||
function M.open_choices(id)
|
||||
P.open, P.choices, P.note = id, nil, nil
|
||||
M.render()
|
||||
L().choices(id, function(choices, why)
|
||||
if P.open ~= id then return end
|
||||
if not choices then
|
||||
P.note = why or "not available now"
|
||||
else
|
||||
P.choices = choices
|
||||
end
|
||||
M.render()
|
||||
cursor_to(function(r) return r.kind == "choice" and r.id == id and (function()
|
||||
for _, c in ipairs(P.choices or {}) do if c.current and c.value == r.value then return true end end
|
||||
return false
|
||||
end)() end)
|
||||
end)
|
||||
end
|
||||
|
||||
--- Enter: on a setting, its choices open (or close, when they are open); on a choice, it is taken.
|
||||
function M.enter()
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
if r.kind == "setting" then
|
||||
if P.open == r.id then return M.close_choices() end
|
||||
return M.open_choices(r.id)
|
||||
elseif r.kind == "choice" then
|
||||
local id, value = r.id, r.value
|
||||
P.open, P.choices, P.note = nil, nil, nil
|
||||
M.render()
|
||||
cursor_to(function(x) return x.kind == "setting" and x.id == id end)
|
||||
L().set(id, value)
|
||||
end
|
||||
end
|
||||
|
||||
--- Esc: the open list closes; with none open, back to the code.
|
||||
function M.back()
|
||||
if M.close_choices() then return end
|
||||
pcall(function() require("llembas.layout").focus("code") end)
|
||||
end
|
||||
|
||||
function M.buffer()
|
||||
if valid() then return P.buf end
|
||||
P.buf = vim.api.nvim_create_buf(false, true)
|
||||
vim.bo[P.buf].buftype = "nofile"
|
||||
vim.bo[P.buf].bufhidden = "hide"
|
||||
vim.bo[P.buf].swapfile = false
|
||||
vim.bo[P.buf].modeline = false
|
||||
vim.bo[P.buf].undolevels = -1
|
||||
vim.bo[P.buf].filetype = "llembas-settings"
|
||||
pcall(vim.api.nvim_buf_set_name, P.buf, "llembas://settings")
|
||||
vim.bo[P.buf].modifiable = false
|
||||
require("llembas.keys").bind("settings", P.buf, { settings_change = M.enter, settings_back = M.back })
|
||||
vim.api.nvim_create_autocmd("User", {
|
||||
group = vim.api.nvim_create_augroup("llembas-lines", { clear = true }),
|
||||
pattern = "LLeMbasChanged",
|
||||
callback = function() if M.win() then M.render() end end,
|
||||
})
|
||||
return P.buf
|
||||
end
|
||||
|
||||
--- The lines as text, and which setting's list is open: for the tests.
|
||||
function M.lines() return valid() and vim.api.nvim_buf_get_lines(P.buf, 0, -1, false) or {} end
|
||||
function M.opened() return P.open end
|
||||
function M.buf() return valid() and P.buf or nil end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,120 @@
|
||||
-- What the person chose in this editor, remembered across restarts: at two levels, for everywhere
|
||||
-- and for a working directory, the directory's own winning. One JSON file in Neovim's state
|
||||
-- directory. Only the editor's own things are here (the mode, the effort, suggestions and AI on or
|
||||
-- off, the bars and their widths): the models are remembered by the LLeMbas CLI and the account.
|
||||
local M = {}
|
||||
|
||||
--- The keys that are kept, and the kind of value each takes.
|
||||
M.KEYS = {
|
||||
mode = "string", effort = "string", autocomplete = "boolean", ai = "boolean",
|
||||
top = "boolean", bottom = "boolean", tree = "boolean", chat = "boolean",
|
||||
tree_width = "number", chat_width = "number", hidden_files = "boolean",
|
||||
}
|
||||
M.MAX_DIRECTORIES = 500
|
||||
M.enabled = true
|
||||
|
||||
function M.path() return vim.fn.stdpath("state") .. "/llembas/settings.json" end
|
||||
|
||||
local function empty() return { version = 1, global = {}, directories = {}, terminals = {}, seq = 0 } end
|
||||
|
||||
local function read()
|
||||
local f = io.open(M.path(), "r")
|
||||
if not f then return empty() end
|
||||
local text = f:read("*a")
|
||||
f:close()
|
||||
local ok, data = pcall(vim.json.decode, text, { luanil = { object = true, array = true } })
|
||||
if not ok or type(data) ~= "table" then return empty() end
|
||||
for _, k in ipairs({ "global", "directories", "terminals" }) do
|
||||
if type(data[k]) ~= "table" or vim.islist(data[k]) and next(data[k]) ~= nil then data[k] = {} end
|
||||
end
|
||||
data.seq = tonumber(data.seq) or 0
|
||||
return data
|
||||
end
|
||||
|
||||
local function write(data)
|
||||
local path = M.path()
|
||||
vim.fn.mkdir(vim.fs.dirname(path), "p", "0700")
|
||||
-- An empty table must be written as an object, or the next read finds a list.
|
||||
for _, k in ipairs({ "global", "directories", "terminals" }) do
|
||||
if next(data[k]) == nil then data[k] = vim.empty_dict() end
|
||||
end
|
||||
local tmp = ("%s.%d.tmp"):format(path, vim.uv.os_getpid())
|
||||
local f = io.open(tmp, "w")
|
||||
if not f then return false end
|
||||
f:write(vim.json.encode(data))
|
||||
f:close()
|
||||
pcall(vim.uv.fs_chmod, tmp, 384) -- 0600
|
||||
local ok = vim.uv.fs_rename(tmp, path)
|
||||
if not ok then pcall(os.remove, tmp) end
|
||||
return ok and true or false
|
||||
end
|
||||
|
||||
--- The directory's name as the store keys it: absolute, links resolved where it exists.
|
||||
function M.dir(cwd)
|
||||
cwd = cwd or vim.fn.getcwd()
|
||||
return vim.uv.fs_realpath(cwd) or vim.fs.normalize(cwd)
|
||||
end
|
||||
|
||||
local function known(level)
|
||||
local out = {}
|
||||
for k, v in pairs(type(level) == "table" and level or {}) do
|
||||
if k ~= "seq" and M.KEYS[k] and type(v) == M.KEYS[k] then out[k] = v end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
--- What is remembered for `cwd`: the machine-wide values, with the directory's own over them.
|
||||
--- Second value: the directory's own entry alone.
|
||||
function M.get(cwd)
|
||||
if not M.enabled then return {}, {} end
|
||||
local data = read()
|
||||
local own = known(data.directories[M.dir(cwd)])
|
||||
return vim.tbl_extend("force", known(data.global), own), own
|
||||
end
|
||||
|
||||
--- Remember `key = value` for the directory (`value` nil forgets it there).
|
||||
function M.set(key, value, cwd)
|
||||
if not M.enabled or not M.KEYS[key] then return false end
|
||||
if value ~= nil and type(value) ~= M.KEYS[key] then return false end
|
||||
local data = read()
|
||||
local dir = M.dir(cwd)
|
||||
local entry = type(data.directories[dir]) == "table" and data.directories[dir] or {}
|
||||
if entry[key] == value then return true end
|
||||
entry[key] = value
|
||||
data.seq = data.seq + 1
|
||||
entry.seq = data.seq
|
||||
data.directories[dir] = entry
|
||||
-- The directories written longest ago go first.
|
||||
local names = vim.tbl_keys(data.directories)
|
||||
if #names > M.MAX_DIRECTORIES then
|
||||
table.sort(names, function(a, b) return (tonumber(data.directories[a].seq) or 0) < (tonumber(data.directories[b].seq) or 0) end)
|
||||
for i = 1, #names - M.MAX_DIRECTORIES do data.directories[names[i]] = nil end
|
||||
end
|
||||
return write(data)
|
||||
end
|
||||
|
||||
--- Make what holds in `cwd` now the machine-wide default: what a directory without a choice of
|
||||
--- its own starts with.
|
||||
function M.make_default(cwd)
|
||||
if not M.enabled then return false end
|
||||
local data = read()
|
||||
local now = vim.tbl_extend("force", known(data.global), known(data.directories[M.dir(cwd)]))
|
||||
data.global = now
|
||||
return write(data)
|
||||
end
|
||||
|
||||
--- Whether the key chords were seen to arrive from the terminal named `id` (nil: never seen).
|
||||
function M.terminal(id)
|
||||
if not M.enabled or not id or id == "" then return nil end
|
||||
return read().terminals[id] == true or nil
|
||||
end
|
||||
|
||||
function M.saw_terminal(id)
|
||||
if not M.enabled or not id or id == "" then return end
|
||||
local data = read()
|
||||
if data.terminals[id] == true then return end
|
||||
data.terminals[id] = true
|
||||
write(data)
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,509 @@
|
||||
-- The file tree: the working directory as lines, in a window on the left. Directories open and
|
||||
-- close, the file you are in is followed and marked, and each row carries one mark of its git
|
||||
-- state. New, rename and delete are asked for in words; nothing is removed without a yes.
|
||||
local M = {}
|
||||
local ns = vim.api.nvim_create_namespace("llembas-tree")
|
||||
|
||||
local T = {
|
||||
buf = nil, root = nil, open = {}, rows = {}, hidden = false, filter = "",
|
||||
git = {}, git_dirs = {}, git_root = nil, branch = nil, current = nil, git_job = 0,
|
||||
}
|
||||
M.SCAN_MAX = 4000 -- how many entries a filter looks through
|
||||
|
||||
--- Asked before anything is deleted. A function of its own so that the tests can answer.
|
||||
function M._confirm(question) return vim.fn.confirm(question, "&Yes\n&No", 2) == 1 end
|
||||
|
||||
--- The program that moves a file to the trash, as a command without the file, or nil.
|
||||
function M._trash()
|
||||
if vim.fn.executable("gio") == 1 then return { "gio", "trash", "--" } end
|
||||
if vim.fn.executable("trash-put") == 1 then return { "trash-put", "--" } end
|
||||
if vim.fn.executable("trash") == 1 then return { "trash" } end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function valid() return T.buf and vim.api.nvim_buf_is_valid(T.buf) end
|
||||
|
||||
function M.win()
|
||||
if not valid() then return nil end
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if vim.api.nvim_win_get_buf(w) == T.buf then return w end
|
||||
end
|
||||
end
|
||||
|
||||
local function scan(dir)
|
||||
local out = {}
|
||||
local fd = vim.uv.fs_scandir(dir)
|
||||
while fd do
|
||||
local name, kind = vim.uv.fs_scandir_next(fd)
|
||||
if not name then break end
|
||||
if kind == "link" or not kind then
|
||||
local st = vim.uv.fs_stat(dir .. "/" .. name)
|
||||
kind = st and st.type or "file"
|
||||
end
|
||||
if name ~= ".git" and (T.hidden or name:sub(1, 1) ~= ".") then
|
||||
out[#out + 1] = { name = name, dir = kind == "directory", path = dir .. "/" .. name }
|
||||
end
|
||||
end
|
||||
table.sort(out, function(a, b)
|
||||
if a.dir ~= b.dir then return a.dir end
|
||||
local x, y = a.name:lower(), b.name:lower()
|
||||
if x ~= y then return x < y end
|
||||
return a.name < b.name
|
||||
end)
|
||||
return out
|
||||
end
|
||||
|
||||
local function relative(path)
|
||||
if path == T.root then return "" end
|
||||
return path:sub(#T.root + 2)
|
||||
end
|
||||
|
||||
local function build()
|
||||
local rows = {}
|
||||
if T.filter ~= "" then
|
||||
-- A filter is a flat list of the files whose path has the text, wherever they are.
|
||||
local needle, seen = T.filter:lower(), 0
|
||||
local function walk(dir)
|
||||
for _, e in ipairs(scan(dir)) do
|
||||
seen = seen + 1
|
||||
if seen > M.SCAN_MAX then return end
|
||||
if e.dir then
|
||||
if e.name ~= "node_modules" then walk(e.path) end
|
||||
elseif relative(e.path):lower():find(needle, 1, true) then
|
||||
rows[#rows + 1] = { path = e.path, name = relative(e.path), dir = false, depth = 0 }
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(T.root)
|
||||
return rows
|
||||
end
|
||||
local function walk(dir, depth)
|
||||
for _, e in ipairs(scan(dir)) do
|
||||
rows[#rows + 1] = { path = e.path, name = e.name, dir = e.dir, depth = depth }
|
||||
if e.dir and T.open[e.path] then walk(e.path, depth + 1) end
|
||||
end
|
||||
end
|
||||
walk(T.root, 0)
|
||||
return rows
|
||||
end
|
||||
|
||||
local MARK_HL = {
|
||||
M = "LLeMbasTreeChanged", A = "LLeMbasTreeAdded", ["?"] = "LLeMbasTreeNew", D = "LLeMbasTreeDeleted",
|
||||
["!"] = "LLeMbasTreeConflict", ["•"] = "LLeMbasTreeChanged",
|
||||
}
|
||||
|
||||
local function mark_of(row)
|
||||
if row.dir then return T.git_dirs[row.path] and "•" or " " end
|
||||
return T.git[row.path] or " "
|
||||
end
|
||||
|
||||
--- A row as its line: the git mark, the indent, the fold mark of a directory, the name.
|
||||
local function line_of(row)
|
||||
local fold = row.dir and (T.open[row.path] and "▾ " or "▸ ") or " "
|
||||
return mark_of(row) .. " " .. (" "):rep(row.depth) .. fold .. row.name .. (row.dir and "/" or "")
|
||||
end
|
||||
|
||||
function M.render()
|
||||
if not valid() then return end
|
||||
T.rows = build()
|
||||
local lines = {}
|
||||
for i, r in ipairs(T.rows) do lines[i] = line_of(r) end
|
||||
if #lines == 0 then lines = { T.filter ~= "" and " (no file has that in its name)" or " (empty)" } end
|
||||
local win = M.win()
|
||||
local at = win and vim.api.nvim_win_get_cursor(win) or nil
|
||||
vim.bo[T.buf].modifiable = true
|
||||
vim.api.nvim_buf_set_lines(T.buf, 0, -1, false, lines)
|
||||
vim.bo[T.buf].modifiable = false
|
||||
vim.api.nvim_buf_clear_namespace(T.buf, ns, 0, -1)
|
||||
for i, r in ipairs(T.rows) do
|
||||
local mark = mark_of(r)
|
||||
if mark ~= " " then
|
||||
vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, 0, { end_col = #mark, hl_group = MARK_HL[mark] or "LLeMbasTreeChanged" })
|
||||
end
|
||||
if r.dir then
|
||||
vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, #mark + 1, { end_col = #lines[i], hl_group = "LLeMbasTreeDirectory" })
|
||||
end
|
||||
if r.path == T.current then
|
||||
vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, 0, { line_hl_group = "LLeMbasTreeCurrent" })
|
||||
end
|
||||
end
|
||||
if win and at then pcall(vim.api.nvim_win_set_cursor, win, { math.min(at[1], #lines), 0 }) end
|
||||
if win then
|
||||
vim.wo[win].winbar = T.filter ~= "" and (" / " .. T.filter:gsub("%%", "%%%%")) or ""
|
||||
end
|
||||
end
|
||||
|
||||
--- The row under the cursor of the tree's window, or nil.
|
||||
local function row_here()
|
||||
local win = M.win()
|
||||
if not win then return nil end
|
||||
return T.rows[vim.api.nvim_win_get_cursor(win)[1]]
|
||||
end
|
||||
|
||||
local function go_to(path)
|
||||
local win = M.win()
|
||||
if not win then return false end
|
||||
for i, r in ipairs(T.rows) do
|
||||
if r.path == path then
|
||||
pcall(vim.api.nvim_win_set_cursor, win, { i, 0 })
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
--- The window a file is opened in: the one the layout says is the code's, else any window with
|
||||
--- an ordinary buffer, else a new one beside the tree.
|
||||
local function code_win()
|
||||
local ok, w = pcall(function() return require("llembas.layout").code_win() end)
|
||||
if ok and w and vim.api.nvim_win_is_valid(w) then return w end
|
||||
for _, win in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
local b = vim.api.nvim_win_get_buf(win)
|
||||
if vim.api.nvim_win_get_config(win).relative == "" and vim.bo[b].buftype == "" then return win end
|
||||
end
|
||||
local tw = M.win()
|
||||
if tw then vim.api.nvim_set_current_win(tw) end
|
||||
vim.cmd("rightbelow vnew")
|
||||
local win = vim.api.nvim_get_current_win()
|
||||
if tw then pcall(vim.api.nvim_win_set_width, tw, M.width or 26) end
|
||||
return win
|
||||
end
|
||||
|
||||
function M.open_file(path)
|
||||
local win = code_win()
|
||||
vim.api.nvim_set_current_win(win)
|
||||
local ok, err = pcall(vim.cmd.edit, vim.fn.fnameescape(path))
|
||||
if not ok then vim.notify("LLeMbas: " .. tostring(err):gsub("^.-:%s*", ""), vim.log.levels.WARN) end
|
||||
end
|
||||
|
||||
--- Enter on a row: a file is opened, a directory opens or closes.
|
||||
function M.activate(only_open)
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
if r.dir then
|
||||
if T.open[r.path] and only_open then return end
|
||||
T.open[r.path] = not T.open[r.path] or nil
|
||||
M.render()
|
||||
go_to(r.path)
|
||||
else
|
||||
M.open_file(r.path)
|
||||
end
|
||||
end
|
||||
|
||||
--- ← on a row: an open directory closes; anything else goes to the directory it is in.
|
||||
function M.collapse()
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
if r.dir and T.open[r.path] then
|
||||
T.open[r.path] = nil
|
||||
M.render()
|
||||
return go_to(r.path)
|
||||
end
|
||||
local parent = vim.fs.dirname(r.path)
|
||||
if parent and parent ~= T.root then go_to(parent) end
|
||||
end
|
||||
|
||||
--- The directory a new file goes into: the directory under the cursor, or the one the file under
|
||||
--- the cursor is in.
|
||||
local function dir_here()
|
||||
local r = row_here()
|
||||
if not r then return T.root end
|
||||
return r.dir and r.path or vim.fs.dirname(r.path)
|
||||
end
|
||||
|
||||
local function inside(path)
|
||||
return path == T.root or vim.startswith(path, T.root .. "/")
|
||||
end
|
||||
|
||||
--- A name typed by the person as a path under `base`; nil when it would leave the tree's root.
|
||||
local function resolve(base, name)
|
||||
name = vim.trim(name or "")
|
||||
if name == "" then return nil end
|
||||
local path = vim.fs.normalize(name:sub(1, 1) == "/" and name or (base .. "/" .. name))
|
||||
if not inside(path) or path == T.root then return nil, "that is outside " .. T.root end
|
||||
return path
|
||||
end
|
||||
|
||||
local function reveal(path)
|
||||
local dir = vim.fs.dirname(path)
|
||||
while dir and inside(dir) and dir ~= T.root do
|
||||
T.open[dir] = true
|
||||
dir = vim.fs.dirname(dir)
|
||||
end
|
||||
end
|
||||
|
||||
--- Make a file, or a directory when the name ends in `/`. Asks for the name when none is given.
|
||||
function M.create(name)
|
||||
local base = dir_here()
|
||||
local function make(text)
|
||||
if not text or not text:match("%S") then return end
|
||||
local is_dir = vim.trim(text):sub(-1) == "/"
|
||||
local path, why = resolve(base, text)
|
||||
if not path then return vim.notify("LLeMbas: not made" .. (why and (": " .. why) or ""), vim.log.levels.WARN) end
|
||||
if vim.uv.fs_stat(path) then return vim.notify("LLeMbas: " .. relative(path) .. " is there already", vim.log.levels.WARN) end
|
||||
if is_dir then
|
||||
vim.fn.mkdir(path, "p")
|
||||
T.open[path] = true
|
||||
else
|
||||
vim.fn.mkdir(vim.fs.dirname(path), "p")
|
||||
local f, err = io.open(path, "w")
|
||||
if not f then return vim.notify("LLeMbas: not made: " .. tostring(err), vim.log.levels.WARN) end
|
||||
f:close()
|
||||
end
|
||||
reveal(path)
|
||||
M.render()
|
||||
go_to(path)
|
||||
M.git_refresh()
|
||||
if not is_dir then M.open_file(path) end
|
||||
end
|
||||
if name then return make(name) end
|
||||
local shown = relative(base)
|
||||
vim.ui.input({ prompt = ("New file in %s/ (a name ending in / makes a directory): "):format(shown == "" and "." or shown) }, make)
|
||||
end
|
||||
|
||||
--- Rename or move the row under the cursor. An open buffer of the file follows it.
|
||||
function M.rename(to)
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
local function move(text)
|
||||
if not text or not text:match("%S") then return end
|
||||
local path, why = resolve(T.root, text)
|
||||
if not path then return vim.notify("LLeMbas: not moved" .. (why and (": " .. why) or ""), vim.log.levels.WARN) end
|
||||
if path == r.path then return end
|
||||
if vim.uv.fs_stat(path) then return vim.notify("LLeMbas: " .. relative(path) .. " is there already", vim.log.levels.WARN) end
|
||||
vim.fn.mkdir(vim.fs.dirname(path), "p")
|
||||
local ok, err = vim.uv.fs_rename(r.path, path)
|
||||
if not ok then return vim.notify("LLeMbas: not moved: " .. tostring(err), vim.log.levels.WARN) end
|
||||
-- Buffers of the file, or of files under the directory, take the new name.
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
local name = vim.api.nvim_buf_get_name(b)
|
||||
if vim.bo[b].buftype == "" and (name == r.path or vim.startswith(name, r.path .. "/")) then
|
||||
local new = path .. name:sub(#r.path + 1)
|
||||
pcall(vim.api.nvim_buf_set_name, b, new)
|
||||
if vim.api.nvim_buf_is_loaded(b) then
|
||||
pcall(vim.api.nvim_buf_call, b, function() vim.cmd("silent! write!") end)
|
||||
end
|
||||
end
|
||||
end
|
||||
if T.open[r.path] then T.open[r.path], T.open[path] = nil, true end
|
||||
if T.current == r.path then T.current = path end
|
||||
reveal(path)
|
||||
M.render()
|
||||
go_to(path)
|
||||
M.git_refresh()
|
||||
end
|
||||
if to then return move(to) end
|
||||
vim.ui.input({ prompt = "Rename or move to: ", default = relative(r.path) }, move)
|
||||
end
|
||||
|
||||
--- Delete the row under the cursor, after asking: to the trash where the system has one.
|
||||
function M.delete()
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
local name = relative(r.path) .. (r.dir and "/" or "")
|
||||
local trash = M._trash()
|
||||
local question = trash and ("Move %s to the trash?"):format(name)
|
||||
or ("Delete %s for good? (No trash was found on this system.)"):format(name)
|
||||
if not M._confirm(question) then return end
|
||||
local ok, why = true, nil
|
||||
if trash then
|
||||
local cmd = vim.list_extend(vim.list_slice(trash), { r.path })
|
||||
local done = vim.system(cmd, { text = true }):wait(15000)
|
||||
ok, why = done.code == 0, vim.trim(done.stderr or "")
|
||||
else
|
||||
ok = vim.fn.delete(r.path, r.dir and "rf" or "") == 0
|
||||
end
|
||||
if not ok then return vim.notify("LLeMbas: not deleted" .. (why and why ~= "" and (": " .. why) or ""), vim.log.levels.WARN) end
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
local bname = vim.api.nvim_buf_get_name(b)
|
||||
if vim.bo[b].buftype == "" and (bname == r.path or vim.startswith(bname, r.path .. "/")) and not vim.bo[b].modified then
|
||||
-- A window keeps its place: the buffer goes, an empty one stands in.
|
||||
for _, w in ipairs(vim.fn.win_findbuf(b)) do
|
||||
pcall(vim.api.nvim_win_call, w, function() vim.cmd("enew") end)
|
||||
end
|
||||
pcall(vim.api.nvim_buf_delete, b, {})
|
||||
end
|
||||
end
|
||||
T.open[r.path] = nil
|
||||
M.render()
|
||||
M.git_refresh()
|
||||
end
|
||||
|
||||
--- Show only the files whose path has `text` (empty: the tree again).
|
||||
function M.set_filter(text)
|
||||
T.filter = text or ""
|
||||
M.render()
|
||||
end
|
||||
|
||||
--- `/`: the filter, typed on the command line and applied at every key.
|
||||
function M.ask_filter()
|
||||
local group = vim.api.nvim_create_augroup("llembas-tree-filter", { clear = true })
|
||||
vim.api.nvim_create_autocmd("CmdlineChanged", {
|
||||
group = group,
|
||||
callback = function()
|
||||
M.set_filter(vim.fn.getcmdline())
|
||||
vim.cmd("redraw")
|
||||
end,
|
||||
})
|
||||
local ok, text = pcall(vim.fn.input, { prompt = "/", default = T.filter, cancelreturn = "" })
|
||||
pcall(vim.api.nvim_del_augroup_by_id, group)
|
||||
M.set_filter(ok and text or "")
|
||||
end
|
||||
|
||||
function M.toggle_hidden(on)
|
||||
if on == nil then T.hidden = not T.hidden else T.hidden = on end
|
||||
pcall(function() require("llembas.store").set("hidden_files", T.hidden) end)
|
||||
M.render()
|
||||
end
|
||||
|
||||
function M.refresh()
|
||||
M.render()
|
||||
M.git_refresh()
|
||||
end
|
||||
|
||||
--- One `git status` for the whole tree, off the main loop; the rows are marked when it answers.
|
||||
function M.git_refresh()
|
||||
if not T.root or vim.fn.executable("git") == 0 then return end
|
||||
T.git_job = T.git_job + 1
|
||||
local job, root = T.git_job, T.root
|
||||
local ok = pcall(vim.system, { "git", "-C", root, "status", "--porcelain=v1", "-z", "--branch", "--untracked-files=normal" },
|
||||
{ text = true, env = { GIT_OPTIONAL_LOCKS = "0" } },
|
||||
vim.schedule_wrap(function(done)
|
||||
if job ~= T.git_job or root ~= T.root then return end
|
||||
local git, dirs, branch = {}, {}, nil
|
||||
if done.code == 0 then
|
||||
local top = vim.trim(vim.fn.system({ "git", "-C", root, "rev-parse", "--show-toplevel" }))
|
||||
local parts = vim.split(done.stdout or "", "\0", { plain = true })
|
||||
local i = 1
|
||||
while i <= #parts do
|
||||
local e = parts[i]
|
||||
if e:sub(1, 2) == "##" then
|
||||
branch = e:sub(4):gsub("%.%.%..*$", ""):gsub("^No commits yet on ", "")
|
||||
elseif #e > 3 then
|
||||
local x, y, path = e:sub(1, 1), e:sub(2, 2), e:sub(4)
|
||||
if x == "R" or x == "C" then i = i + 1 end -- the name it had follows
|
||||
local mark = (x == "U" or y == "U" or (x == "A" and y == "A") or (x == "D" and y == "D")) and "!"
|
||||
or (x == "?" and "?") or ((x == "D" or y == "D") and "D") or ((x == "A") and "A") or "M"
|
||||
local full = top .. "/" .. path:gsub("/$", "")
|
||||
git[full] = mark
|
||||
local dir = full
|
||||
if path:sub(-1) == "/" then dirs[full] = true end
|
||||
while true do
|
||||
dir = vim.fs.dirname(dir)
|
||||
if not dir or #dir < #top or dirs[dir] then break end
|
||||
dirs[dir] = true
|
||||
end
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
T.git, T.git_dirs, T.branch = git, dirs, branch
|
||||
M.render()
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
end))
|
||||
if not ok then T.git, T.git_dirs = {}, {} end
|
||||
end
|
||||
|
||||
--- The branch the tree's directory is on, or nil (not a repository, or not asked yet).
|
||||
function M.branch() return T.branch end
|
||||
|
||||
--- The file in `buf` is the one you are in: its directories open, its row is marked and shown.
|
||||
function M.follow(buf)
|
||||
if not valid() or T.filter ~= "" then return end
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
if name == "" or vim.bo[buf].buftype ~= "" or not T.root then return end
|
||||
name = vim.fs.normalize(name)
|
||||
if not vim.startswith(name, T.root .. "/") or name == T.current then return end
|
||||
T.current = name
|
||||
reveal(name)
|
||||
M.render()
|
||||
go_to(name)
|
||||
end
|
||||
|
||||
local function buffer()
|
||||
if valid() then return T.buf end
|
||||
T.buf = vim.api.nvim_create_buf(false, true)
|
||||
vim.bo[T.buf].buftype = "nofile"
|
||||
vim.bo[T.buf].bufhidden = "hide"
|
||||
vim.bo[T.buf].swapfile = false
|
||||
vim.bo[T.buf].modeline = false
|
||||
vim.bo[T.buf].undolevels = -1
|
||||
vim.bo[T.buf].filetype = "llembas-tree"
|
||||
pcall(vim.api.nvim_buf_set_name, T.buf, "llembas://tree")
|
||||
vim.bo[T.buf].modifiable = false
|
||||
require("llembas.keys").bind("tree", T.buf, {
|
||||
tree_open = function() M.activate(false) end,
|
||||
tree_close = M.collapse,
|
||||
tree_new = function() M.create() end,
|
||||
tree_rename = function() M.rename() end,
|
||||
tree_delete = M.delete,
|
||||
tree_filter = M.ask_filter,
|
||||
tree_hidden = function() M.toggle_hidden() end,
|
||||
tree_refresh = M.refresh,
|
||||
})
|
||||
-- → only opens: an open directory stays open (Enter and l open and close).
|
||||
vim.keymap.set("n", "<Right>", function() M.activate(true) end, { buffer = T.buf, nowait = true, silent = true, desc = "LLeMbas: Open the file, or the directory" })
|
||||
vim.keymap.set("n", "<2-LeftMouse>", function() M.activate(false) end, { buffer = T.buf, nowait = true, silent = true, desc = "LLeMbas: Open the file; open or close the directory" })
|
||||
local group = vim.api.nvim_create_augroup("llembas-tree", { clear = true })
|
||||
vim.api.nvim_create_autocmd("BufEnter", { group = group, callback = function(ev) M.follow(ev.buf) end })
|
||||
vim.api.nvim_create_autocmd({ "BufWritePost", "FocusGained" }, { group = group, callback = function() if M.win() then M.refresh() end end })
|
||||
vim.api.nvim_create_autocmd("DirChanged", {
|
||||
group = group,
|
||||
callback = function()
|
||||
if vim.v.event.scope == "global" and M.win() then M.set_root(vim.fn.getcwd()) end
|
||||
end,
|
||||
})
|
||||
return T.buf
|
||||
end
|
||||
|
||||
function M.set_root(dir)
|
||||
dir = vim.fs.normalize(vim.uv.fs_realpath(dir) or dir)
|
||||
if dir == T.root then return end
|
||||
T.root, T.open, T.git, T.git_dirs, T.branch, T.current, T.filter = dir, {}, {}, {}, nil, nil, ""
|
||||
M.refresh()
|
||||
end
|
||||
|
||||
--- Open the tree's window on the left, `width` columns. Returns the window. The focus stays.
|
||||
function M.open(width)
|
||||
require("llembas.ui").setup_highlights()
|
||||
buffer()
|
||||
M.width = width or M.width or 26
|
||||
local win = M.win()
|
||||
if win then return win end
|
||||
if not T.root then
|
||||
T.root = vim.fs.normalize(vim.uv.fs_realpath(vim.fn.getcwd()) or vim.fn.getcwd())
|
||||
local remembered = require("llembas.store").get()
|
||||
if remembered.hidden_files ~= nil then T.hidden = remembered.hidden_files end
|
||||
end
|
||||
local back = vim.api.nvim_get_current_win()
|
||||
vim.cmd("topleft vertical " .. M.width .. "split")
|
||||
win = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(win, T.buf)
|
||||
for k, v in pairs({
|
||||
wrap = false, number = false, relativenumber = false, signcolumn = "no", foldcolumn = "0", list = false,
|
||||
cursorline = true, winfixwidth = true, spell = false, statuscolumn = "",
|
||||
}) do
|
||||
vim.api.nvim_set_option_value(k, v, { scope = "local", win = win })
|
||||
end
|
||||
vim.wo[win].fillchars = "eob: "
|
||||
if vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back) end
|
||||
M.render()
|
||||
M.git_refresh()
|
||||
local cur = vim.api.nvim_get_current_buf()
|
||||
M.follow(cur)
|
||||
return win
|
||||
end
|
||||
|
||||
function M.close()
|
||||
local win = M.win()
|
||||
if win and #vim.api.nvim_tabpage_list_wins(0) > 1 then pcall(vim.api.nvim_win_close, win, true) end
|
||||
end
|
||||
|
||||
function M.is_open() return M.win() ~= nil end
|
||||
|
||||
--- The tree's lines as text, and its rows: for the tests and for anyone drawing it elsewhere.
|
||||
function M.lines() return valid() and vim.api.nvim_buf_get_lines(T.buf, 0, -1, false) or {} end
|
||||
function M.buf() return valid() and T.buf or nil end
|
||||
M._state = T
|
||||
|
||||
return M
|
||||
+38
-1
@@ -33,6 +33,32 @@ local HIGHLIGHTS = {
|
||||
LLeMbasStatusModel = { link = "Comment" },
|
||||
LLeMbasStatusBusy = { link = "DiagnosticWarn" },
|
||||
LLeMbasStatusAttach = { link = "DiagnosticHint" },
|
||||
-- The bars.
|
||||
LLeMbasBar = { link = "StatusLine" },
|
||||
LLeMbasBarKey = { link = "Special" },
|
||||
LLeMbasBarTitle = { link = "Title" },
|
||||
LLeMbasBarSeparator = { link = "WinSeparator" },
|
||||
LLeMbasBarFact = { link = "Comment" },
|
||||
LLeMbasBarIdle = { link = "DiagnosticOk" },
|
||||
LLeMbasBarBusy = { link = "DiagnosticWarn" },
|
||||
LLeMbasBarWaiting = { link = "DiagnosticInfo" },
|
||||
LLeMbasBarOff = { link = "Comment" },
|
||||
LLeMbasBarVim = { link = "StatusLine" },
|
||||
-- The prompt and the settings lines.
|
||||
LLeMbasPromptPrefix = { link = "Special" },
|
||||
LLeMbasChip = { link = "DiagnosticHint" },
|
||||
LLeMbasLineLabel = { link = "Comment" },
|
||||
LLeMbasLineValue = { link = "Normal" },
|
||||
LLeMbasLineOff = { link = "Comment" },
|
||||
LLeMbasLineCurrent = { link = "Title" },
|
||||
-- The tree.
|
||||
LLeMbasTreeDirectory = { link = "Directory" },
|
||||
LLeMbasTreeCurrent = { link = "Visual" },
|
||||
LLeMbasTreeChanged = { link = "DiagnosticWarn" },
|
||||
LLeMbasTreeAdded = { link = "DiagnosticOk" },
|
||||
LLeMbasTreeNew = { link = "DiagnosticHint" },
|
||||
LLeMbasTreeDeleted = { link = "DiagnosticError" },
|
||||
LLeMbasTreeConflict = { link = "DiagnosticError" },
|
||||
}
|
||||
|
||||
local hi_installed = false
|
||||
@@ -78,7 +104,18 @@ function M.progress_bar(done, total, width)
|
||||
end
|
||||
|
||||
--- Welcome virtual lines shown in an empty transcript (never written to the buffer text).
|
||||
function M.welcome_virt_lines()
|
||||
function M.welcome_virt_lines(narrow)
|
||||
if narrow then
|
||||
-- For a bar of 34 columns: no line is wider than 32.
|
||||
return {
|
||||
{ { "", "Normal" } },
|
||||
{ { " ◈ ", "LLeMbasBrand" }, { "LLeMbas", "LLeMbasUserHeader" } },
|
||||
{ { " Waybread for the code ahead.", "LLeMbasNote" } },
|
||||
{ { "", "Normal" } },
|
||||
{ { " Type below; Enter sends.", "LLeMbasNote" } },
|
||||
{ { " Tab: ask, rewrite or add.", "LLeMbasNote" } },
|
||||
}
|
||||
end
|
||||
return {
|
||||
{ { "", "Normal" } },
|
||||
{ { " ◈ ", "LLeMbasBrand" }, { "LLeMbas", "LLeMbasUserHeader" }, { " · Waybread for the code ahead.", "LLeMbasNote" } },
|
||||
|
||||
+23
-4
@@ -27,10 +27,29 @@ cmd("LLeMbasAccept", function(o) require("llembas.diff").accept(o.bang) end, { b
|
||||
cmd("LLeMbasReject", function(o) require("llembas.diff").reject(o.bang) end, { bang = true, desc = "LLeMbas: reject the change under the cursor (! all)" })
|
||||
cmd("LLeMbasNextHunk", function() require("llembas.diff").next_hunk() end, { desc = "LLeMbas: jump to next proposed change" })
|
||||
cmd("LLeMbasPrevHunk", function() require("llembas.diff").prev_hunk() end, { desc = "LLeMbas: jump to previous proposed change" })
|
||||
cmd("LLeMbasAutocomplete", function(o)
|
||||
local on = require("llembas.complete").auto(o.args == "on" and true or o.args == "off" and false or nil)
|
||||
vim.notify("LLeMbas: suggestions as you type are " .. (on and "on" or "off"))
|
||||
end, { nargs = "?", complete = function() return { "on", "off" } end, desc = "LLeMbas: suggestions as you type on or off" })
|
||||
local function on_off(arg) if arg == "on" then return true elseif arg == "off" then return false end end
|
||||
local function on_off_words() return { "on", "off" } end
|
||||
cmd("LLeMbasAutocomplete", function(o) L().autocomplete(on_off(o.args)) end,
|
||||
{ nargs = "?", complete = on_off_words, desc = "LLeMbas: suggestions as you type on or off" })
|
||||
cmd("LLeMbasAI", function(o) L().ai(on_off(o.args)) end,
|
||||
{ nargs = "?", complete = on_off_words, desc = "LLeMbas: everything of LLeMbas on or off (off: a plain editor)" })
|
||||
cmd("LLeMbasEffort", function(o) L().effort(o.args) end,
|
||||
{ nargs = "?", complete = function() return L().EFFORTS end, desc = "LLeMbas: the effort of the conversation" })
|
||||
cmd("LLeMbasPrompt", function(o)
|
||||
local intent = o.args ~= "" and o.args or nil
|
||||
if o.range > 0 then L().prompt({ intent = intent, first = o.line1, last = o.line2 }) else L().prompt({ intent = intent }) end
|
||||
end, { range = true, nargs = "?", complete = function() return { "ask", "rewrite", "add" } end,
|
||||
desc = "LLeMbas: to the prompt with the lines or the cursor's line (ask, rewrite or add)" })
|
||||
cmd("LLeMbasMenu", function() L().menu() end, { desc = "LLeMbas: every command and every setting" })
|
||||
cmd("LLeMbasTree", function() require("llembas.layout").toggle("tree") end, { desc = "LLeMbas: the file tree, show and hide" })
|
||||
cmd("LLeMbasBars", function(o)
|
||||
local layout = require("llembas.layout")
|
||||
local a = o.fargs
|
||||
if #a == 0 then return L().setup({ bars = not layout.options().on and true or false }) end
|
||||
if a[1] == "on" or a[1] == "off" then return L().setup({ bars = a[1] == "on" }) end
|
||||
layout.toggle(a[1], on_off(a[2]))
|
||||
end, { nargs = "*", complete = function() return { "on", "off", "top", "bottom", "tree", "chat" } end,
|
||||
desc = "LLeMbas: the four bars on or off, or one of them (top, bottom, tree, chat) [on|off]" })
|
||||
cmd("LLeMbasAutocompleteTokens", function(o) L().autocomplete_tokens(o.args) end,
|
||||
{ nargs = "?", complete = function() return { "auto", "words", "line", "block", "file", "24", "64", "256", "1024", "2048" } end,
|
||||
desc = "LLeMbas: set autocomplete max tokens or prediction length preset" })
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The stand-in agent (tests/fake_agent.py) with one thing more: it keeps the effort it is given.
|
||||
|
||||
The shared stand-in answers every effort with `default`. The layout's tests set the effort from
|
||||
the settings lines and need the answer to say the level that is used, as the LLeMbas CLI does:
|
||||
a level this "model" offers (low, medium, high, off) is used as asked, and any other is read as
|
||||
its start level, `medium`. Everything else is the shared stand-in's, run unchanged.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
fake = os.path.join(here, "..", "..", "tests", "fake_agent.py")
|
||||
with open(fake, encoding="utf-8") as f:
|
||||
source = f.read().rstrip()
|
||||
if not source.endswith("\nmain()"):
|
||||
sys.exit("agent_levels: tests/fake_agent.py no longer ends by calling main()")
|
||||
ns = {"__name__": "fake_agent", "__file__": fake}
|
||||
exec(compile(source[: -len("main()")], fake, "exec"), ns)
|
||||
|
||||
OFFERED = ("off", "low", "medium", "high")
|
||||
level = {"now": None}
|
||||
shared_handle, shared_out = ns["handle"], ns["out"]
|
||||
|
||||
|
||||
def taken(asked):
|
||||
return asked if asked in OFFERED else "medium"
|
||||
|
||||
|
||||
def handle(msg):
|
||||
params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
|
||||
if msg.get("method") == "session/new":
|
||||
asked = (params.get("_meta") or {}).get("effort")
|
||||
level["now"] = taken(asked) if isinstance(asked, str) else None
|
||||
if msg.get("method") == "_lembas/configure" and isinstance(params.get("effort"), str):
|
||||
level["now"] = taken(params["effort"])
|
||||
return shared_handle(msg)
|
||||
|
||||
|
||||
def out(msg):
|
||||
# A `model` event says the effort too, as the CLI's does.
|
||||
event = (msg.get("params") or {}).get("event") if msg.get("method") == "_lembas/event" else None
|
||||
if level["now"] and isinstance(event, dict) and event.get("type") == "model":
|
||||
event["effort"] = level["now"]
|
||||
result = msg.get("result")
|
||||
if level["now"] and isinstance(result, dict):
|
||||
if "effort" in result:
|
||||
result["effort"] = level["now"]
|
||||
inner = (result.get("_meta") or {}).get("lembas")
|
||||
if isinstance(inner, dict) and "effort" in inner:
|
||||
inner["effort"] = level["now"]
|
||||
shared_out(msg)
|
||||
|
||||
|
||||
ns["handle"], ns["out"] = handle, out
|
||||
ns["main"]()
|
||||
@@ -0,0 +1,72 @@
|
||||
-- One start of Neovim with the plugin, for the checks that need a new process: what is remembered
|
||||
-- from one start to the next, and what is written to the terminal on the way in and out.
|
||||
-- Run by nvim/tests/layout.lua in the directory under test; $STEP says what to do. The answer is
|
||||
-- one line on standard output: RESULT {json}. Standard error is left to the plugin alone.
|
||||
local step = vim.env.STEP or "look"
|
||||
local repo = assert(vim.env.LLEMBAS_TEST_REPO, "LLEMBAS_TEST_REPO")
|
||||
local agent = repo .. "/nvim/tests/agent_levels.py"
|
||||
local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end
|
||||
|
||||
local function finish(data)
|
||||
io.stdout:write("RESULT " .. vim.json.encode(data) .. "\n")
|
||||
pcall(function() require("llembas").restart(true) end)
|
||||
vim.cmd("qa!")
|
||||
end
|
||||
|
||||
vim.schedule(function()
|
||||
local ok, err = xpcall(function()
|
||||
vim.notify = function() end
|
||||
vim.o.columns, vim.o.lines = 160, 45
|
||||
vim.g.mapleader = " "
|
||||
vim.cmd("runtime plugin/llembas.lua")
|
||||
local L = require("llembas")
|
||||
if step == "plain" then
|
||||
L.setup({ cmd = { "python3", agent } })
|
||||
return finish({ plain = true })
|
||||
end
|
||||
L.setup({ cmd = { "python3", agent }, bars = true })
|
||||
local layout = require("llembas.layout")
|
||||
local keys = require("llembas.keys")
|
||||
local chat = require("llembas.chat")
|
||||
vim.wait(50)
|
||||
local out = {}
|
||||
if step == "start" then return finish({ started = true }) end
|
||||
if step == "chords" then return finish({ chords = keys.chords(), guess = keys._terminal_reports() }) end
|
||||
if step == "change" then
|
||||
L.mode("edit")
|
||||
-- (Until the agent has answered: its event says the new mode before its answer does.)
|
||||
wait(function() return require("llembas.store").get().mode == "edit" end)
|
||||
L.effort("high")
|
||||
wait(function() return L._state.effort == "high" end)
|
||||
L.autocomplete(false)
|
||||
layout.toggle("tree", false)
|
||||
-- The right bar dragged wider: remembered on the way out.
|
||||
vim.api.nvim_win_set_width(vim.fn.bufwinid(chat.tbuf), 46)
|
||||
elseif step == "change_b" then
|
||||
L.mode("plan")
|
||||
wait(function() return require("llembas.store").get().mode == "plan" end)
|
||||
elseif step == "session" then
|
||||
local done = false
|
||||
L.choices("mode", function() done = true end)
|
||||
wait(function() return done end)
|
||||
for _, line in ipairs(vim.fn.readfile(vim.env.FAKE_AGENT_LOG)) do
|
||||
local m = vim.json.decode(line)
|
||||
if m.method == "session/new" then out.new_mode, out.new_effort = (m.params._meta or {}).mode, (m.params._meta or {}).effort end
|
||||
end
|
||||
elseif step == "default" then
|
||||
require("llembas.store").make_default()
|
||||
elseif step == "ai_off" then
|
||||
L.ai(false)
|
||||
end
|
||||
layout.remember_widths()
|
||||
local s, o = L.settings(), layout.options()
|
||||
out.mode, out.effort, out.autocomplete, out.ai = s.mode, s.effort, s.autocomplete, s.ai
|
||||
out.tree, out.chat, out.chat_width, out.tree_width = o.tree, o.chat, o.chat_width, o.tree_width
|
||||
out.tree_open = require("llembas.tree").is_open()
|
||||
finish(out)
|
||||
end, debug.traceback)
|
||||
if not ok then
|
||||
io.stdout:write("CHILD FAILED " .. tostring(err) .. "\n")
|
||||
vim.cmd("cquit!")
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,726 @@
|
||||
-- The four bars, tested on the plugin alone (no distribution): what is on the screen at three
|
||||
-- sizes, the keys, the prompt's intent and attachment, the settings lines, the tree, what is
|
||||
-- remembered, and what is said to the terminal. Against the stand-in agent.
|
||||
-- Run by scripts/test-nvim.sh, with a screen (no -l), so that the bars are read as drawn:
|
||||
-- nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -c "luafile nvim/tests/layout.lua"
|
||||
local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h")
|
||||
local repo = vim.fs.normalize(here .. "/../..")
|
||||
vim.opt.rtp:append(repo .. "/nvim")
|
||||
local levels = here .. "/agent_levels.py"
|
||||
local child = here .. "/child.lua"
|
||||
local work = vim.env.LLEMBAS_NVIM_TEST_WORK
|
||||
local own_work = false
|
||||
if not work or work == "" then
|
||||
-- Run by hand: a state directory of the test's own all the same.
|
||||
work = vim.fn.tempname()
|
||||
own_work = true
|
||||
vim.fn.mkdir(work .. "/state", "p")
|
||||
vim.env.XDG_STATE_HOME = work .. "/state"
|
||||
end
|
||||
work = vim.uv.fs_realpath(work)
|
||||
local tmp = work .. "/layout-project"
|
||||
local log = work .. "/layout-agent.log"
|
||||
vim.fn.mkdir(tmp .. "/src/deep", "p")
|
||||
vim.env.FAKE_AGENT_LOG = log
|
||||
vim.env.PYTHONDONTWRITEBYTECODE = "1"
|
||||
-- Whatever terminal this is run in says nothing about itself to the plugin.
|
||||
for _, name in ipairs({ "LLEMBAS_TERM", "LLEMBAS_TTY", "TMUX", "STY", "ZELLIJ", "KITTY_WINDOW_ID", "GHOSTTY_RESOURCES_DIR", "TERM_PROGRAM" }) do vim.env[name] = nil end
|
||||
vim.env.TERM = "dumb"
|
||||
|
||||
local failed, ran = 0, 0
|
||||
local function say(text) io.stdout:write(text .. "\n") end
|
||||
local function check(name, cond, extra)
|
||||
ran = ran + 1
|
||||
if cond then say("ok " .. name) else
|
||||
failed = failed + 1
|
||||
say("FAIL " .. name .. (extra ~= nil and ("\n " .. (type(extra) == "string" and extra or vim.inspect(extra))) or ""))
|
||||
end
|
||||
end
|
||||
local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end
|
||||
local function t(keys) return vim.api.nvim_replace_termcodes(keys, true, false, true) end
|
||||
local function feed(keys) vim.api.nvim_feedkeys(t(keys), "mx", false) end
|
||||
local function sent()
|
||||
local out = {}
|
||||
for _, line in ipairs(vim.fn.filereadable(log) == 1 and vim.fn.readfile(log) or {}) do out[#out + 1] = vim.json.decode(line) end
|
||||
return out
|
||||
end
|
||||
local function calls(method)
|
||||
local out = {}
|
||||
for _, m in ipairs(sent()) do if m.method == method then out[#out + 1] = m.params end end
|
||||
return out
|
||||
end
|
||||
local function last_call(method) local c = calls(method); return c[#c] end
|
||||
local function row(r)
|
||||
vim.cmd("redraw")
|
||||
local out = {}
|
||||
for c = 1, vim.o.columns do out[#out + 1] = vim.fn.screenstring(r, c) end
|
||||
return table.concat(out)
|
||||
end
|
||||
local function top() return row(1) end
|
||||
local function bottom() return row(vim.o.lines - 1) end
|
||||
local function rtrim(s) return (s:gsub("%s+$", "")) end
|
||||
--- `text` in exactly `w` cells, padded with spaces (the tests' own, not the layout's).
|
||||
local function cell(text, w) return text .. (" "):rep(w - vim.fn.strdisplaywidth(text)) end
|
||||
local function width(s) return vim.fn.strdisplaywidth(s) end
|
||||
local function keys_part() return rtrim(vim.fn.strcharpart(bottom(), 0, vim.o.columns - (vim.o.columns < 60 and 15 or vim.o.columns < 120 and 20 or 35))) end
|
||||
--- Neovim's own segment at the right end. At full width its last six cells are the pending
|
||||
--- operator's (`%S`, Neovim's own text, which keys fed by a test leave things in): not compared.
|
||||
local function vim_part()
|
||||
local n = vim.o.columns < 60 and 15 or vim.o.columns < 120 and 20 or 35
|
||||
return vim.fn.strcharpart(bottom(), vim.o.columns - n, n == 35 and 29 or n)
|
||||
end
|
||||
local function wins()
|
||||
local out = {}
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if vim.api.nvim_win_get_config(w).relative == "" then
|
||||
local b = vim.api.nvim_win_get_buf(w)
|
||||
local ft = vim.bo[b].filetype
|
||||
local name = vim.api.nvim_buf_get_name(b)
|
||||
local kind = ft == "llembas-tree" and "tree" or ft == "llembas-settings" and "settings"
|
||||
or name:match("llembas://chat$") and "chat" or name:match("llembas://prompt$") and "prompt" or "code"
|
||||
out[kind] = { win = w, width = vim.api.nvim_win_get_width(w), height = vim.api.nvim_win_get_height(w) }
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
local function kinds(w)
|
||||
local names = vim.tbl_keys(w)
|
||||
table.sort(names)
|
||||
return table.concat(names, " ")
|
||||
end
|
||||
local function resize(cols, rows)
|
||||
vim.o.columns, vim.o.lines = cols, rows
|
||||
vim.api.nvim_exec_autocmds("VimResized", {})
|
||||
vim.wait(60)
|
||||
vim.cmd("redraw")
|
||||
end
|
||||
local said_msgs = {}
|
||||
local function was_said(text) return table.concat(said_msgs, "|"):find(text, 1, true) ~= nil end
|
||||
|
||||
--- Run a child Neovim (nvim/tests/child.lua) in `dir` with `env`; returns its stdout, stderr and code.
|
||||
local function run_child(dir, env)
|
||||
local e = vim.tbl_extend("force", { PYTHONDONTWRITEBYTECODE = "1", LLEMBAS_TEST_REPO = repo, TERM = "dumb" }, env or {})
|
||||
local done = vim.system({ vim.v.progpath, "--headless", "-u", "NONE", "-i", "NONE", "--cmd", "set rtp+=" .. repo .. "/nvim",
|
||||
"-c", "luafile " .. child }, { cwd = dir, env = e, text = false }):wait(40000)
|
||||
return done.stdout or "", done.stderr or "", done.code
|
||||
end
|
||||
local function child_json(dir, env)
|
||||
local out, err, code = run_child(dir, env)
|
||||
local line = out:match("RESULT (%b{})")
|
||||
local ok, data = pcall(vim.json.decode, line or "", { luanil = { object = true, array = true } })
|
||||
return ok and data or { failed = true, out = out, err = err, code = code }
|
||||
end
|
||||
|
||||
local function run()
|
||||
vim.notify = function(m) said_msgs[#said_msgs + 1] = tostring(m) end
|
||||
vim.g.mapleader = " "
|
||||
vim.cmd("cd " .. vim.fn.fnameescape(tmp))
|
||||
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, tmp .. "/sample.py")
|
||||
vim.fn.writefile({ "x = 1" }, tmp .. "/src/util.py")
|
||||
vim.fn.writefile({ "y = 2" }, tmp .. "/src/deep/inner.py")
|
||||
vim.fn.writefile({ "# readme" }, tmp .. "/README.md")
|
||||
vim.fn.writefile({ "secret" }, tmp .. "/.env.example")
|
||||
vim.cmd("runtime plugin/llembas.lua")
|
||||
|
||||
local L = require("llembas")
|
||||
local chat = require("llembas.chat")
|
||||
local layout = require("llembas.layout")
|
||||
local keys = require("llembas.keys")
|
||||
local tree = require("llembas.tree")
|
||||
local lines = require("llembas.lines")
|
||||
local store = require("llembas.store")
|
||||
local C = require("llembas.complete")
|
||||
|
||||
-- ── The plugin on its own: nothing of the bars unless asked for. ────────────────────────────────
|
||||
L.setup({ cmd = { "python3", levels } })
|
||||
check("alone: without `bars` no tabline, no statusline of ours, no window but the one",
|
||||
vim.o.tabline == "" and not vim.o.statusline:find("llembas", 1, true) and #vim.api.nvim_tabpage_list_wins(0) == 1)
|
||||
check("alone: without `keys` no key is mapped", vim.fn.maparg("<C-S-A>", "n") == "" and vim.fn.maparg("<Space>la", "n") == ""
|
||||
and vim.fn.maparg("<M-Right>", "n") == "")
|
||||
check("alone: the public functions are there", type(L.settings) == "function" and type(L.setting_lines) == "function"
|
||||
and type(L.choices) == "function" and type(L.set) == "function" and type(L.prompt) == "function" and type(L.intent) == "function"
|
||||
and type(L.effort) == "function" and type(L.ai) == "function" and type(L.menu) == "function")
|
||||
local s0 = L.settings()
|
||||
check("alone: settings() says idle, no session, AI and suggestions on, the intent ask",
|
||||
s0.state == "idle" and s0.session == false and s0.ai == true and s0.autocomplete == true and s0.intent == "ask" and s0.model == nil, s0)
|
||||
|
||||
-- ── One option turns the bars on. 160×45. ───────────────────────────────────────────────────────
|
||||
vim.o.columns, vim.o.lines = 160, 45
|
||||
L.setup({ bars = true })
|
||||
vim.cmd("edit " .. vim.fn.fnameescape(tmp .. "/sample.py"))
|
||||
local fbuf = vim.api.nvim_get_current_buf()
|
||||
vim.wait(100)
|
||||
local w = wins()
|
||||
check("160×45: the windows are tree, code, settings, chat and prompt", kinds(w) == "chat code prompt settings tree", kinds(w))
|
||||
check("160×45: the tree is 26 columns, the right bar 42, the code has the rest",
|
||||
w.tree.width == 26 and w.chat.width == 42 and w.settings.width == 42 and w.prompt.width == 42 and w.code.width == 160 - 26 - 42 - 2, w)
|
||||
check("160×45: the settings are four lines, the prompt three and its chip's row", w.settings.height == 4 and w.prompt.height == 4, w)
|
||||
check("160×45: the focus is in the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
check("160×45: the top bar, cell for cell",
|
||||
top() == " ● idle │ " .. cell("no conversation yet", 160 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6)
|
||||
.. " │ " .. cell("— · — · —", 32) .. " │ ctx — │ AC on ", top())
|
||||
check("160×45: the bottom bar in the code shows the keys that always arrive (no chord was seen)",
|
||||
keys_part() == " Spc la ask · Tab accept suggestion · Alt+→ one word · Spc lp menu · Alt+←→ bars · Spc lb tree · Spc ll chat", keys_part())
|
||||
check("160×45: and Neovim's own state at its right end, in cells of fixed width",
|
||||
vim_part() == " NOR" .. (" "):rep(19) .. "1:1 ", "[" .. vim_part() .. "]")
|
||||
check("the bars are exactly as wide as the screen", width(top()) == 160 and width(bottom()) == 160)
|
||||
|
||||
-- Every width from 30 to 220: the rows are exactly that wide, never wrapped, never short.
|
||||
local bad = {}
|
||||
for cols = 30, 220 do
|
||||
if width(layout.top_text(cols)) ~= cols then bad[#bad + 1] = "top " .. cols end
|
||||
for _, where in ipairs({ "code", "tree", "prompt", "settings", "chat", "change" }) do
|
||||
local seg = cols < 60 and 15 or cols < 120 and 20 or 35
|
||||
if width(layout.bottom_text(where, cols)) > cols - seg then bad[#bad + 1] = where .. " " .. cols end
|
||||
end
|
||||
end
|
||||
check("every width from 30 to 220: the top bar is exactly that wide and the keys never pass their room", #bad == 0, bad)
|
||||
local _, cut = layout.fit({ { text = "a title that is much too long to fit", flex = true, min = 8, prio = 2 }, { text = "x", width = 5, prio = 1 } }, 24)
|
||||
check("a text that does not fit its cell is cut with an ellipsis; nothing wraps", cut == " a title that … │ x " and width(cut) == 24, "[" .. cut .. "]")
|
||||
|
||||
-- ── The keys: one table. ────────────────────────────────────────────────────────────────────────
|
||||
local missing = {}
|
||||
local function mapped(mode, lhs, buf)
|
||||
local m = vim.fn.maparg(lhs, mode, false, true)
|
||||
if next(m) == nil then return false end
|
||||
if buf then return m.buffer == 1 end
|
||||
return true
|
||||
end
|
||||
for _, k in ipairs(keys.table) do
|
||||
if not k.virtual then
|
||||
if k.chord then
|
||||
for _, mode in ipairs({ "n", "x", "i" }) do
|
||||
if not mapped(mode, k.chord) then missing[#missing + 1] = mode .. " " .. k.chord end
|
||||
end
|
||||
end
|
||||
if not k.scope then
|
||||
for _, lhs in ipairs(keys.alts(k)) do
|
||||
for _, mode in ipairs(k.modes or { "n" }) do
|
||||
if not mapped(mode, keys.lhs(lhs)) then missing[#missing + 1] = mode .. " " .. keys.lhs(lhs) end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: every chord and every key after the prefix of the table is mapped", #missing == 0, missing)
|
||||
local in_table = {}
|
||||
for _, k in ipairs(keys.table) do
|
||||
for _, lhs in ipairs(type(k.chord) == "table" and k.chord or { k.chord }) do in_table[t(lhs)] = true end
|
||||
for _, lhs in ipairs(keys.alts(k)) do in_table[t(keys.lhs(lhs))] = true end
|
||||
end
|
||||
local strays = {}
|
||||
for _, mode in ipairs({ "n", "x", "i" }) do
|
||||
for _, m in ipairs(vim.api.nvim_get_keymap(mode)) do
|
||||
if (m.desc or ""):match("^LLeMbas: ") and not in_table[t(m.lhs)] and t(m.lhs) ~= t(L.config.complete.trigger) then strays[#strays + 1] = mode .. " " .. m.lhs end
|
||||
end
|
||||
end
|
||||
check("keys: every mapping of LLeMbas's is in the table (but the one that asks for a suggestion, a setting)", #strays == 0, strays)
|
||||
local shown_unbound = {}
|
||||
for _, where in ipairs({ "code", "tree", "prompt", "settings", "chat", "change" }) do
|
||||
for _, form in ipairs({ true, false }) do
|
||||
for _, k in ipairs(keys.for_bar(where, form)) do
|
||||
local e = keys.by_id[k.id]
|
||||
if not (e.chord or #keys.alts(e) > 0) then shown_unbound[#shown_unbound + 1] = where .. " " .. k.id end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: nothing the bottom bar can show is without a key", #shown_unbound == 0, shown_unbound)
|
||||
check("keys: a key is written as the owner's table writes it",
|
||||
keys.written("<C-S-A>") == "^⇧A" and keys.written("<M-C-S-Y>") == "Alt+^⇧Y" and keys.written("<C-Tab>") == "^Tab"
|
||||
and keys.written("<C-M-m>") == "Alt+^M" and keys.written("<M-Left>") == "Alt+←" and keys.written("<Prefix>a") == "Spc la"
|
||||
and keys.written("<CR>") == "Enter", { keys.written("<C-M-m>"), keys.written("<Prefix>a") })
|
||||
|
||||
-- The bars' own keys, in their buffers.
|
||||
local scoped = {}
|
||||
local bufs = { tree = tree.buf(), settings = lines.buf(), prompt = chat.ibuf, chat = chat.tbuf }
|
||||
for _, k in ipairs(keys.table) do
|
||||
if k.scope and bufs[k.scope] and not k.virtual then
|
||||
for _, lhs in ipairs(keys.alts(k)) do
|
||||
local m = vim.api.nvim_buf_call(bufs[k.scope], function()
|
||||
return { vim.fn.maparg(lhs, "n", false, true).buffer, vim.fn.maparg(lhs, "i", false, true).buffer }
|
||||
end)
|
||||
if m[1] ~= 1 and m[2] ~= 1 then scoped[#scoped + 1] = k.scope .. " " .. lhs end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: every key of the tree, the settings lines, the prompt and the transcript is mapped in its buffer", #scoped == 0, scoped)
|
||||
|
||||
-- ── The bottom bar follows the focus. ───────────────────────────────────────────────────────────
|
||||
layout.focus("tree")
|
||||
check("focus tree: the bar shows the tree's keys",
|
||||
keys_part() == " Enter open · a new · r rename · d delete · / filter · Alt+→ code · . hidden files · Spc la ask · Spc lp menu · Spc lb tree", keys_part())
|
||||
feed("<M-Right>")
|
||||
check("Alt+→ from the tree is the code", vim.api.nvim_get_current_buf() == fbuf and layout.where() == "code")
|
||||
feed("<M-Right>")
|
||||
check("Alt+→ from the code is the prompt", vim.api.nvim_get_current_buf() == chat.ibuf and layout.where() == "prompt")
|
||||
check("focus prompt: the bar shows the prompt's keys",
|
||||
keys_part() == " Enter send · Tab ask/rewrite/add · Spc lm mode · Spc lM model · Esc back to code · Spc l. stop", keys_part())
|
||||
feed("<M-Left>")
|
||||
check("Alt+← from the prompt is the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
vim.api.nvim_set_current_win(w.settings.win)
|
||||
check("focus settings: the bar shows the settings' keys", keys_part() == " Enter change · ↑↓ move · Esc back · Alt+← code", keys_part())
|
||||
vim.api.nvim_set_current_win(w.chat.win)
|
||||
check("focus transcript: the bar shows the transcript's keys",
|
||||
keys_part() == " Enter open file · K tool output · i prompt · Alt+← code · Spc l. stop · Spc la ask · Spc lp menu · Spc ll chat", keys_part())
|
||||
layout.focus("code")
|
||||
|
||||
-- A chord that arrives proves the terminal reports them: from then the bar shows the chords.
|
||||
check("chords: none seen, none assumed (no terminal says it reports them)", keys.chords() == false)
|
||||
feed("<C-S-E>")
|
||||
check("Ctrl+Shift+E hides the tree", wait(function() return not tree.is_open() end) and wins().code.width == 160 - 43)
|
||||
check("chords: one arrived, so they arrive", keys.chords() == true)
|
||||
check("chords: that is remembered for this terminal", store.terminal(keys._terminal_id()) == true, keys._terminal_id())
|
||||
feed("<C-S-E>")
|
||||
check("Ctrl+Shift+E shows it again, 26 columns", wait(function() return tree.is_open() end) and wins().tree.width == 26)
|
||||
check("code, chords: the owner's line",
|
||||
keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars · ^⇧E tree · ^⇧D chat", keys_part())
|
||||
layout.focus("tree")
|
||||
check("tree, chords: the owner's line",
|
||||
vim.startswith(keys_part(), " Enter open · a new · r rename · d delete · / filter · Alt+→ code"), keys_part())
|
||||
layout.focus("chat")
|
||||
check("prompt, chords: the owner's line",
|
||||
vim.startswith(keys_part(), " Enter send · Tab ask/rewrite/add · ^Tab mode · ^⇧M model · Esc back to code"), keys_part())
|
||||
vim.api.nvim_set_current_win(wins().settings.win)
|
||||
check("settings, chords: the owner's line", vim.startswith(keys_part(), " Enter change · ↑↓ move · Esc back"), keys_part())
|
||||
layout.focus("code")
|
||||
feed("<C-S-D>")
|
||||
check("Ctrl+Shift+D hides the right bar: settings, chat and prompt", wait(function() return not chat.is_open() end) and kinds(wins()) == "code tree", kinds(wins()))
|
||||
feed("<C-S-D>")
|
||||
check("Ctrl+Shift+D shows it again", wait(function() return chat.is_open() end) and kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
|
||||
check("the focus stayed in the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
|
||||
-- ── The prompt: its prefix, Tab, the attachment. ────────────────────────────────────────────────
|
||||
local function prompt_rows()
|
||||
local pw = wins().prompt.win
|
||||
local pos = vim.fn.win_screenpos(pw)
|
||||
local out = {}
|
||||
for r = pos[1], pos[1] + vim.api.nvim_win_get_height(pw) - 1 do
|
||||
out[#out + 1] = vim.fn.strcharpart(row(r), pos[2] - 1, vim.api.nvim_win_get_width(pw))
|
||||
end
|
||||
return out
|
||||
end
|
||||
local pr = prompt_rows()
|
||||
check("prompt: the row above it is the chip's and is empty; the first line begins with what Enter does",
|
||||
rtrim(pr[1]) == "" and pr[2] == "ask ›" .. (" "):rep(42 - 5), pr)
|
||||
layout.focus("chat")
|
||||
feed("<Tab>")
|
||||
check("Tab in an empty prompt: rewrite", L.intent() == "rewrite" and vim.startswith(prompt_rows()[2], "rewrite › "), prompt_rows())
|
||||
feed("<Tab>")
|
||||
check("Tab again: add", L.intent() == "add" and vim.startswith(prompt_rows()[2], "add › "), prompt_rows())
|
||||
feed("i<Tab>")
|
||||
check("Tab again, while typing: ask", L.intent() == "ask" and vim.startswith(prompt_rows()[2], "ask › "), prompt_rows())
|
||||
check("Tab in an empty prompt leaves it empty", table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), "") == "")
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "some text" })
|
||||
vim.bo[chat.ibuf].expandtab = false
|
||||
feed("A<Tab>")
|
||||
check("Tab with text in the prompt is Neovim's own Tab, and what Enter does stays",
|
||||
L.intent() == "ask" and vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false)[1] == "some text\t", vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false))
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "a long line that is wider than the bar and so goes on to a second row of the prompt" })
|
||||
local wrapped = prompt_rows()
|
||||
check("a long prompt keeps one left edge: the rows under the first are indented by the prefix",
|
||||
vim.startswith(wrapped[2], "ask › a long") and vim.startswith(wrapped[3], (" "):rep(10)) and wrapped[3]:sub(11, 11) ~= " ", wrapped)
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
|
||||
feed("<Esc>")
|
||||
check("Esc in the prompt is back in the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
|
||||
-- A selection comes along.
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("Vj<C-S-A>")
|
||||
check("Ctrl+Shift+A with a selection: the prompt has the focus and the chip names the lines",
|
||||
vim.api.nvim_get_current_buf() == chat.ibuf and rtrim(prompt_rows()[1]) == " sample.py:1-2", prompt_rows())
|
||||
check("…and it is an ask", L.intent() == "ask" and L.settings().attachment == "sample.py:1-2")
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "META what is this?" })
|
||||
feed("<CR>")
|
||||
check("Enter sends", wait(function() return last_call("session/prompt") ~= nil end) and wait(function() return not L._state.busy end))
|
||||
local p = last_call("session/prompt")
|
||||
local ed = ((p._meta or {}).lembas or {}).editor
|
||||
check("ask: the question goes with the selection as the editor's context",
|
||||
ed and ed.selection and ed.selection.start == 1 and ed.selection["end"] == 2 and ed.selection.text == "def a():\n return 1"
|
||||
and p.prompt[#p.prompt].text == "META what is this?", p)
|
||||
check("ask: the transcript names what came along", chat.text():find("[sample.py:1-2]\nMETA what is this?", 1, true) ~= nil, chat.text())
|
||||
check("ask: the chip is gone and the prompt is empty", rtrim(prompt_rows()[1]) == "" and L.settings().attachment == nil
|
||||
and table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), "") == "")
|
||||
check("a session started: the top bar and the settings lines say the model, the mode, the effort and the context",
|
||||
wait(function() return L.settings().context == 4 end)
|
||||
and top():find("│ " .. cell("model-a · manual · default", 32) .. " │ ctx 4% │ AC on ", 1, true) ~= nil
|
||||
and vim.deep_equal(lines.lines(), { "model model-a", "mode manual", "effort default", "autocomplete on" }),
|
||||
{ top(), lines.lines() })
|
||||
check("idle again", vim.startswith(top(), " ● idle │ "), top())
|
||||
|
||||
-- A bare cursor: the line comes along as a point.
|
||||
layout.focus("code")
|
||||
vim.api.nvim_win_set_cursor(0, { 4, 0 })
|
||||
feed(" la")
|
||||
check("<Space>la without a selection: the cursor's line comes along as a point",
|
||||
vim.api.nvim_get_current_buf() == chat.ibuf and rtrim(prompt_rows()[1]) == " sample.py:4", prompt_rows())
|
||||
feed("<Esc>")
|
||||
|
||||
-- Rewrite: the selection is rewritten in place, shown as changes.
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("Vj le")
|
||||
check("<Space>le with a selection: the prompt says rewrite and carries the lines",
|
||||
vim.api.nvim_get_current_buf() == chat.ibuf and L.intent() == "rewrite" and vim.startswith(prompt_rows()[2], "rewrite › ")
|
||||
and rtrim(prompt_rows()[1]) == " sample.py:1-2", prompt_rows())
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "REPLACE def a():\\n return 100" })
|
||||
local before = #calls("session/prompt")
|
||||
feed("<CR>")
|
||||
check("rewrite: the lines go to the rewrite, not to the chat",
|
||||
wait(function() return last_call("_lembas/edit") ~= nil end) and last_call("_lembas/edit").text == "def a():\n return 1"
|
||||
and #calls("session/prompt") == before, last_call("_lembas/edit"))
|
||||
check("rewrite: shown in the file as a change, nothing written", wait(function() return require("llembas.diff").pending(fbuf) == 1 end)
|
||||
and vim.api.nvim_buf_get_lines(fbuf, 1, 2, false)[1] == " return 1")
|
||||
check("rewrite: the focus is in the code, and what Enter does is ask again",
|
||||
vim.api.nvim_get_current_buf() == fbuf and L.intent() == "ask" and L.settings().attachment == nil)
|
||||
check("on a proposed change, chords: the owner's line",
|
||||
wait(function() return keys_part() == " ^⇧Y accept · ^⇧J reject · ]h next · Alt+^⇧Y accept all · [h previous · ^⇧P menu" end), keys_part())
|
||||
local change = {}
|
||||
for _, k in ipairs(keys.table) do
|
||||
if k.scope == "change" then
|
||||
for _, lhs in ipairs(keys.alts(k)) do
|
||||
if vim.fn.maparg(lhs, "n", false, true).buffer ~= 1 then change[#change + 1] = lhs end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: with a change shown, the change's own keys are mapped in the buffer", #change == 0, change)
|
||||
feed("<C-S-Y>")
|
||||
check("Ctrl+Shift+Y accepts it", vim.api.nvim_buf_get_lines(fbuf, 1, 2, false)[1] == " return 100" and require("llembas.diff").pending(fbuf) == 0)
|
||||
check("…and the bar is the code's again", wait(function() return vim.startswith(keys_part(), " ^⇧A ask") end), keys_part())
|
||||
|
||||
-- Add: new code at the point.
|
||||
vim.api.nvim_win_set_cursor(0, { 3, 0 })
|
||||
feed(" lg")
|
||||
check("<Space>lg: the prompt says add", L.intent() == "add" and vim.startswith(prompt_rows()[2], "add › ") and rtrim(prompt_rows()[1]) == " sample.py:3", prompt_rows())
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "REPLACE # a comment" })
|
||||
feed("<CR>")
|
||||
check("add: asked for at the point, and shown as a change",
|
||||
wait(function() return require("llembas.diff").pending(fbuf) == 1 end) and last_call("_lembas/edit").instruction == "At this line, REPLACE # a comment",
|
||||
last_call("_lembas/edit"))
|
||||
feed("<C-S-J>")
|
||||
check("Ctrl+Shift+J rejects it", require("llembas.diff").pending(fbuf) == 0 and vim.api.nvim_buf_get_lines(fbuf, 2, 3, false)[1] == "")
|
||||
|
||||
-- ── Tab's three jobs never collide. ─────────────────────────────────────────────────────────────
|
||||
C._typing = function() return true end
|
||||
vim.api.nvim_win_set_cursor(0, { 5, 12 })
|
||||
C.request(true)
|
||||
check("a suggestion is shown, and <Tab> is the buffer's while it is", wait(function() return C.visible() end)
|
||||
and vim.fn.maparg("<Tab>", "i", false, true).buffer == 1 and vim.fn.maparg("<M-Right>", "i", false, true).buffer == 1)
|
||||
C.accept()
|
||||
check("accepted: <Tab> is nobody's in the code again (Neovim's own)", not C.visible() and vim.fn.maparg("<Tab>", "i", false, true).buffer ~= 1)
|
||||
check("Alt+→ in the code without a suggestion is the bars' key, with one it was the suggestion's",
|
||||
(vim.fn.maparg("<M-Right>", "i", false, true).desc or ""):find("bar on the right", 1, true) ~= nil)
|
||||
vim.cmd("silent undo")
|
||||
|
||||
-- ── The settings lines: Enter opens the choices in place. ──────────────────────────────────────
|
||||
vim.api.nvim_set_current_win(wins().settings.win)
|
||||
vim.api.nvim_win_set_cursor(0, { 2, 0 })
|
||||
feed("<CR>")
|
||||
check("Enter on mode: its choices open under the line, in the bar, the current one marked",
|
||||
wait(function() return #lines.lines() == 8 end)
|
||||
and vim.deep_equal(vim.list_slice(lines.lines(), 2, 6), { "mode manual", " ● manual", " ○ edit", " ○ auto", " ○ plan" })
|
||||
and wins().settings.height == 8 and vim.api.nvim_win_get_cursor(0)[1] == 3, { lines.lines(), wins().settings })
|
||||
check("…and no window floats in the middle of the screen", (function()
|
||||
for _, win in ipairs(vim.api.nvim_list_wins()) do if vim.api.nvim_win_get_config(win).relative ~= "" then return false end end
|
||||
return true
|
||||
end)())
|
||||
feed("j<CR>")
|
||||
check("Enter on a choice sets it through the agent, the list closes, the line and the top bar follow",
|
||||
wait(function() return L._state.mode == "edit" end) and last_call("session/set_mode").modeId == "edit"
|
||||
and wait(function() return lines.lines()[2] == "mode edit" and #lines.lines() == 4 end)
|
||||
and top():find("model-a · edit · default", 1, true) ~= nil and wins().settings.height == 4, { lines.lines(), top() })
|
||||
vim.api.nvim_win_set_cursor(0, { 3, 0 })
|
||||
feed("<CR>")
|
||||
check("Enter on effort: the levels", wait(function() return #lines.lines() == 4 + #L.EFFORTS end) and lines.lines()[4] == " ○ off", lines.lines())
|
||||
feed("<Esc>")
|
||||
check("Esc closes the choices and stays in the lines", #lines.lines() == 4 and layout.where() == "settings")
|
||||
L.set("effort", "high")
|
||||
check("effort: set through the agent (`_lembas/configure`), and shown",
|
||||
wait(function() return (last_call("_lembas/configure") or {}).effort == "high" end)
|
||||
and wait(function() return lines.lines()[3] == "effort high" end) and top():find("model-a · edit · high", 1, true) ~= nil, { lines.lines(), top() })
|
||||
said_msgs = {}
|
||||
L.set("effort", "xhigh")
|
||||
check("effort: a level the model does not offer is said, with the level it runs on",
|
||||
wait(function() return was_said("does not offer the effort xhigh; it runs on medium") end) and L.settings().effort == "medium", said_msgs)
|
||||
L.set("effort", "high")
|
||||
wait(function() return L.settings().effort == "high" end)
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("<CR>")
|
||||
check("Enter on model: the account's models, by name", wait(function() return #lines.lines() == 7 end)
|
||||
and vim.deep_equal(vim.list_slice(lines.lines(), 2, 4), { " ● Model A", " ○ Model B", " ○ Model C" }), lines.lines())
|
||||
feed("j<CR>")
|
||||
check("model: set through the agent, and shown", wait(function() return L._state.model == "example/model-b" end)
|
||||
and wait(function() return lines.lines()[1] == "model model-b" end), lines.lines())
|
||||
vim.api.nvim_win_set_cursor(0, { 4, 0 })
|
||||
feed("<CR>j<CR>")
|
||||
check("autocomplete: off from its line; the top bar says so", wait(function() return L.settings().autocomplete == false end)
|
||||
and wait(function() return lines.lines()[4] == "autocomplete off" end) and top():find("│ AC off ", 1, true) ~= nil, { lines.lines(), top() })
|
||||
L.set("autocomplete", "on")
|
||||
feed("<Esc>")
|
||||
check("Esc from the lines is back in the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
feed("<C-Tab>")
|
||||
check("Ctrl+Tab switches to the next mode", wait(function() return L._state.mode == "auto" end), L._state.mode)
|
||||
|
||||
-- The state the top bar says.
|
||||
layout.focus("chat")
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "SLOW" })
|
||||
feed("<CR>")
|
||||
check("a turn runs: the top bar says what the agent does", wait(function() return top():match("^ ◐ %a+ ") ~= nil end)
|
||||
and (L.settings().state == "writing" or L.settings().state == "thinking" or L.settings().state == "tools"), top())
|
||||
feed("<C-S-G>")
|
||||
check("Ctrl+Shift+G stops it", wait(function() return not L._state.busy end) and wait(function() return vim.startswith(top(), " ● idle ") end), top())
|
||||
local asked
|
||||
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts, cb = cb } end
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "PERM" })
|
||||
feed("<CR>")
|
||||
check("the agent asks: the top bar says it waits for you", wait(function() return asked ~= nil end)
|
||||
and wait(function() return vim.startswith(top(), " ● waiting for you │ ") end), top())
|
||||
asked.cb(asked.items[1])
|
||||
wait(function() return not L._state.busy end)
|
||||
|
||||
-- The menu has every command and every setting, effort among them.
|
||||
asked = nil
|
||||
feed("<C-S-P>")
|
||||
local menu = {}
|
||||
for _, i in ipairs(asked and asked.items or {}) do menu[#menu + 1] = asked.opts.format_item(i) end
|
||||
local menu_text = table.concat(menu, "\n")
|
||||
check("Ctrl+Shift+P: the menu has the settings — model, mode, effort, autocomplete — and the commands with their keys",
|
||||
menu_text:find("Model: example/model-b", 1, true) and menu_text:find("Mode: auto", 1, true) and menu_text:find("Effort: high", 1, true)
|
||||
and menu_text:find("Autocomplete: on", 1, true) and menu_text:find("Tree: shown", 1, true)
|
||||
and menu_text:find("Stop the running turn [^⇧G]", 1, true) and menu_text:find("Earlier conversations [Spc ls]", 1, true), menu_text)
|
||||
local in_menu = {}
|
||||
for _, k in ipairs(keys.table) do
|
||||
if k.run and not k.scope and not menu_text:find(k.desc, 1, true) then in_menu[#in_menu + 1] = k.id end
|
||||
end
|
||||
check("…every action of the key table is in the menu", #in_menu == 0, in_menu)
|
||||
for _, i in ipairs(asked.items) do
|
||||
if i.text:match("^Effort") then
|
||||
local inner
|
||||
vim.ui.select = function(items, _, cb) inner = items; cb("low") end
|
||||
i.run()
|
||||
check("menu: Effort opens the levels, and the one picked is set", inner and vim.deep_equal(inner, L.EFFORTS)
|
||||
and wait(function() return L.settings().effort == "low" end), inner)
|
||||
end
|
||||
end
|
||||
layout.focus("code")
|
||||
|
||||
-- ── 100×30 and 80×24: the bars fold. ────────────────────────────────────────────────────────────
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
vim.bo[fbuf].modified = false
|
||||
resize(100, 30)
|
||||
w = wins()
|
||||
check("100×30: the chat folds away, the tree stays", kinds(w) == "code tree" and w.tree.width == 26 and w.code.width == 73, w)
|
||||
check("100×30: the top bar, narrower cells",
|
||||
top() == " ● idle │ " .. cell("conversation", 100 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-b · auto · low", 32) .. " │ ctx 4% │ AC on ", top())
|
||||
check("100×30: the bottom bar is cut by priority, and Neovim's state is the short one",
|
||||
keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars" and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ",
|
||||
{ keys_part(), "[" .. vim_part() .. "]" })
|
||||
check("100×30: both rows are 100 wide", width(top()) == 100 and width(bottom()) == 100)
|
||||
check("100×30: the layout says what is folded", layout.options().folded.chat == true and layout.options().folded.tree == false)
|
||||
feed("<C-S-D>")
|
||||
check("100×30: Ctrl+Shift+D shows the chat all the same", wait(function() return chat.is_open() end) and wins().chat.width == 42, wins())
|
||||
feed("<C-S-D>")
|
||||
wait(function() return not chat.is_open() end)
|
||||
L._state.busy = false
|
||||
resize(80, 24)
|
||||
w = wins()
|
||||
check("80×24: only the code, all 80 columns", kinds(w) == "code" and w.code.width == 80, w)
|
||||
check("80×24: the top bar",
|
||||
top() == " ● idle │ " .. cell("conversation", 80 - 2 - 9 - 3 - 3 - 26 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-b · auto · low", 26) .. " │ ctx 4% │ AC on ", top())
|
||||
check("80×24: the bottom bar", keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu" and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ",
|
||||
{ keys_part(), "[" .. vim_part() .. "]" })
|
||||
check("80×24: both rows are 80 wide", width(top()) == 80 and width(bottom()) == 80)
|
||||
feed("<M-Right>")
|
||||
check("80×24: Alt+→ opens the chat and goes to its prompt", chat.is_open() and vim.api.nvim_get_current_buf() == chat.ibuf)
|
||||
feed("<Esc>")
|
||||
resize(50, 12)
|
||||
check("50×12: still one row each, exactly as wide, the least needed gone", width(top()) == 50 and width(bottom()) == 50
|
||||
and vim.startswith(top(), " ● idle │ ") and vim_part() == " NOR" .. (" "):rep(5) .. "1:1 ", { top(), bottom() })
|
||||
resize(160, 14)
|
||||
w = wins()
|
||||
check("160×14: too low for the settings lines; the prompt is one row", kinds(w) == "chat code prompt tree" and w.prompt.height == 2, w)
|
||||
resize(160, 45)
|
||||
check("160×45 again: everything is back", kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
|
||||
|
||||
-- Neovim's own state in the bottom bar.
|
||||
layout.focus("code")
|
||||
vim.api.nvim_buf_set_lines(fbuf, 0, 1, false, { "def a(): # changed" })
|
||||
feed("qq")
|
||||
check("modified and recording: the flags are in their cells", vim_part() == " NOR + @q" .. (" "):rep(14) .. "1:1 ", "[" .. vim_part() .. "]")
|
||||
feed("q")
|
||||
vim.api.nvim_win_set_cursor(0, { 2, 4 })
|
||||
check("the cursor's line and column", vim_part():sub(-10) == " 2:5 ", "[" .. vim_part() .. "]")
|
||||
vim.cmd("silent! undo")
|
||||
|
||||
-- ── The tree. ───────────────────────────────────────────────────────────────────────────────────
|
||||
check("tree: the directory as lines, directories first, the file you are in shown",
|
||||
vim.deep_equal(tree.lines(), { " ▸ src/", " README.md", " sample.py" }), tree.lines())
|
||||
layout.focus("tree")
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("<CR>")
|
||||
check("tree: Enter opens a directory", vim.deep_equal(tree.lines(), { " ▾ src/", " ▸ deep/", " util.py", " README.md", " sample.py" }), tree.lines())
|
||||
feed("<Left>")
|
||||
check("tree: ← closes it", tree.lines()[1] == " ▸ src/" and #tree.lines() == 3, tree.lines())
|
||||
feed("<Right><Right>")
|
||||
check("tree: → opens it and leaves it open", tree.lines()[1] == " ▾ src/" and #tree.lines() == 5, tree.lines())
|
||||
vim.api.nvim_win_set_cursor(0, { 3, 0 })
|
||||
feed("<CR>")
|
||||
check("tree: Enter on a file opens it in the code's window", vim.api.nvim_buf_get_name(0) == tmp .. "/src/util.py" and layout.where() == "code")
|
||||
vim.cmd("edit " .. vim.fn.fnameescape(tmp .. "/src/deep/inner.py"))
|
||||
check("tree: the file you are in is followed — its directories open, its row under the tree's cursor",
|
||||
tree.lines()[3] == " inner.py" and vim.api.nvim_win_get_cursor(tree.win())[1] == 3, tree.lines())
|
||||
layout.focus("tree")
|
||||
feed(".")
|
||||
check("tree: . shows hidden files", vim.tbl_contains(tree.lines(), " .env.example"), tree.lines())
|
||||
feed(".")
|
||||
check("tree: . hides them again", not vim.tbl_contains(tree.lines(), " .env.example"))
|
||||
tree.set_filter("inner")
|
||||
check("tree: a filter shows the files whose path has the text", vim.deep_equal(tree.lines(), { " src/deep/inner.py" }), tree.lines())
|
||||
tree.set_filter("")
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
tree.create("new/thing.py")
|
||||
check("tree: a new file, its directories made, opened", vim.fn.filereadable(tmp .. "/src/new/thing.py") == 1
|
||||
and vim.api.nvim_buf_get_name(0) == tmp .. "/src/new/thing.py", tree.lines())
|
||||
layout.focus("tree")
|
||||
tree.create("../../../outside.py")
|
||||
tree.create("/somewhere/else.py")
|
||||
check("tree: nothing is made outside the tree's directory", vim.fn.filereadable(vim.fs.dirname(tmp) .. "/outside.py") == 0 and vim.fn.isdirectory("/somewhere") == 0)
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
tree.create("pkg/")
|
||||
check("tree: a name ending in / makes a directory", vim.fn.isdirectory(tmp .. "/src/pkg") == 1)
|
||||
for i, l in ipairs(tree.lines()) do if l:find("thing.py", 1, true) then vim.api.nvim_win_set_cursor(tree.win(), { i, 0 }) end end
|
||||
tree.rename("src/pkg/renamed.py")
|
||||
check("tree: rename moves the file, and its open buffer with it", vim.fn.filereadable(tmp .. "/src/pkg/renamed.py") == 1
|
||||
and vim.fn.filereadable(tmp .. "/src/new/thing.py") == 0 and vim.fn.bufnr(tmp .. "/src/pkg/renamed.py") ~= -1, tree.lines())
|
||||
local question
|
||||
tree._confirm = function(q) question = q; return false end
|
||||
tree._trash = function() return nil end
|
||||
tree.delete()
|
||||
check("tree: delete asks first, and says when there is no trash; a no deletes nothing",
|
||||
question == "Delete src/pkg/renamed.py for good? (No trash was found on this system.)" and vim.fn.filereadable(tmp .. "/src/pkg/renamed.py") == 1, question)
|
||||
local trash = work .. "/trash.sh"
|
||||
vim.fn.writefile({ "#!/bin/sh", 'mkdir -p "' .. work .. '/trashed" && mv "$1" "' .. work .. '/trashed/"' }, trash)
|
||||
vim.fn.setfperm(trash, "rwx------")
|
||||
tree._trash = function() return { trash } end
|
||||
tree._confirm = function(q) question = q; return true end
|
||||
tree.delete()
|
||||
check("tree: with a trash the file goes there", question == "Move src/pkg/renamed.py to the trash?"
|
||||
and vim.fn.filereadable(tmp .. "/src/pkg/renamed.py") == 0 and vim.fn.filereadable(work .. "/trashed/renamed.py") == 1, question)
|
||||
if vim.fn.executable("git") == 1 then
|
||||
vim.fn.system({ "git", "-C", tmp, "init", "-q", "-b", "trunk" })
|
||||
vim.fn.system({ "git", "-C", tmp, "add", "README.md" })
|
||||
tree.refresh()
|
||||
check("tree: one git mark a row — a new file, an added one, a directory with changes inside",
|
||||
wait(function() return vim.tbl_contains(tree.lines(), "? sample.py") end, 5000) and vim.tbl_contains(tree.lines(), "A README.md")
|
||||
and tree.lines()[1] == "• ▾ src/", tree.lines())
|
||||
check("the top bar's right end has the branch when it fits", wait(function() return top():find("│ trunk ", 1, true) ~= nil end, 3000), top())
|
||||
end
|
||||
layout.focus("code")
|
||||
vim.cmd("edit " .. vim.fn.fnameescape(tmp .. "/sample.py"))
|
||||
|
||||
-- ── AI off: a plain editor. ─────────────────────────────────────────────────────────────────────
|
||||
local agent = L._state.conn and L._state.conn.proc.pid
|
||||
feed("<C-S-I>")
|
||||
check("Ctrl+Shift+I: LLeMbas is off — the agent is stopped, the chat put away, the top bar says so",
|
||||
L.settings().ai == false and L._state.conn == nil and wait(function() return not chat.is_open() end)
|
||||
and vim.startswith(top(), " ● AI off │ ") and kinds(wins()) == "code tree", { top(), kinds(wins()) })
|
||||
check("AI off: the agent's process ends", wait(function() return not (agent and vim.uv.kill(agent, 0) == 0) end, 7000))
|
||||
local n_complete = #calls("_lembas/complete")
|
||||
C.request(false)
|
||||
vim.wait(200)
|
||||
check("AI off: no suggestion is asked for", #calls("_lembas/complete") == n_complete)
|
||||
said_msgs = {}
|
||||
feed("<C-S-A>")
|
||||
check("AI off: asking says that it is off, and opens nothing", was_said("LLeMbas is off") and not chat.is_open(), said_msgs)
|
||||
feed("<C-S-I>")
|
||||
check("Ctrl+Shift+I again: on, and the chat is back", L.settings().ai == true and wait(function() return chat.is_open() end))
|
||||
|
||||
-- ── Each bar can be switched off. ───────────────────────────────────────────────────────────────
|
||||
layout.toggle("top", false)
|
||||
check("the top bar off: Neovim's own tabline setting is back", vim.o.showtabline ~= 2 and vim.o.tabline == "")
|
||||
layout.toggle("bottom", false)
|
||||
check("the bottom bar off: Neovim's own statusline is back", vim.o.statusline == "")
|
||||
layout.toggle("top", true)
|
||||
layout.toggle("bottom", true)
|
||||
check("…and on again", vim.startswith(top(), " ● idle") and vim.startswith(keys_part(), " ^⇧A ask"), { top(), keys_part() })
|
||||
|
||||
-- ── Remembered across restarts, per directory. ──────────────────────────────────────────────────
|
||||
local dir_a, dir_b, dir_c = work .. "/dir-a", work .. "/dir-b", work .. "/dir-c"
|
||||
for _, d in ipairs({ dir_a, dir_b, dir_c }) do vim.fn.mkdir(d, "p") end
|
||||
local state_home = work .. "/remember-state"
|
||||
vim.fn.mkdir(state_home, "p")
|
||||
local env = { XDG_STATE_HOME = state_home, FAKE_AGENT_LOG = work .. "/remember.log", PATH = vim.env.PATH, HOME = vim.env.HOME }
|
||||
local function step(dir, name, more) return child_json(dir, vim.tbl_extend("force", env, { STEP = name }, more or {})) end
|
||||
local r = step(dir_a, "change")
|
||||
check("remember: in a first directory the mode, the effort, suggestions and the bars are changed", r.mode == "edit" and r.effort == "high"
|
||||
and r.autocomplete == false and r.tree == false and r.chat_width == 46, r)
|
||||
r = step(dir_b, "look")
|
||||
check("remember: another directory knows nothing of that", r.mode == nil and r.effort == nil and r.autocomplete == true and r.tree == true and r.chat_width == 42, r)
|
||||
r = step(dir_b, "change_b")
|
||||
check("remember: and is changed in its own way", r.mode == "plan" and r.tree == true, r)
|
||||
r = step(dir_a, "look")
|
||||
check("remember: the first directory, started again, has what was chosen there — before any session",
|
||||
r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false and r.chat_width == 46 and r.tree_open == false, r)
|
||||
r = step(dir_a, "session")
|
||||
check("remember: a session there starts on that mode and that effort", r.new_mode == "edit" and r.new_effort == "high" and r.mode == "edit" and r.effort == "high", r)
|
||||
r = step(dir_b, "look")
|
||||
check("remember: the second directory has its own", r.mode == "plan" and r.effort == nil and r.autocomplete == true and r.tree == true, r)
|
||||
r = step(dir_a, "default")
|
||||
r = step(dir_c, "look")
|
||||
check("remember: made the default, the first directory's choices are what a new directory starts with",
|
||||
r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false, r)
|
||||
r = step(dir_b, "look")
|
||||
check("remember: and a directory keeps what it chose itself (the mode), over the default it now takes the rest from",
|
||||
r.mode == "plan" and r.effort == "high" and r.tree == false, r)
|
||||
r = step(dir_a, "ai_off")
|
||||
r = step(dir_a, "look")
|
||||
check("remember: AI off is remembered too", r.ai == false, r)
|
||||
local f = io.open(state_home .. "/nvim/llembas/settings.json")
|
||||
local stored = f and vim.json.decode(f:read("*a")) or {}
|
||||
if f then f:close() end
|
||||
check("remember: one file in Neovim's state directory, with a machine-wide level and one per directory, and no model in it",
|
||||
stored.global and stored.global.mode == "edit" and stored.directories[dir_a].mode == "edit" and stored.directories[dir_b].mode == "plan"
|
||||
and stored.directories[dir_a].model == nil and stored.global.model == nil, stored)
|
||||
local perm = vim.uv.fs_stat(state_home .. "/nvim/llembas/settings.json")
|
||||
check("remember: the file is the person's alone (0600)", perm and bit.band(perm.mode, 511) == 384, perm and bit.band(perm.mode, 511))
|
||||
|
||||
-- ── The terminal: the user var. ─────────────────────────────────────────────────────────────────
|
||||
local set, clear = "\27]1337;SetUserVar=llembas_ide=MQ==\7", "\27]1337;SetUserVar=llembas_ide=\7"
|
||||
check("user var: the bytes are OSC 1337 SetUserVar with base64 of 1, and an empty value to clear",
|
||||
layout.uservar_bytes("1") == set and layout.uservar_bytes("") == clear)
|
||||
local _, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start", LLEMBAS_TERM = "1" }))
|
||||
check("user var: in the LLeMbas terminal it is set on start and cleared on exit, and nothing else is written",
|
||||
err == set .. clear, vim.inspect(err))
|
||||
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start", LLEMBAS_TTY = "pane-1" }))
|
||||
check("user var: $LLEMBAS_TTY counts as well", err == set .. clear, vim.inspect(err))
|
||||
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start" }))
|
||||
check("user var: in any other terminal nothing is written", err == "", vim.inspect(err))
|
||||
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start", LLEMBAS_TERM = "1", TMUX = "/tmp/tmux-1/default,1,0" }))
|
||||
check("user var: inside tmux it is wrapped for tmux to pass on",
|
||||
err == "\27Ptmux;\27\27]1337;SetUserVar=llembas_ide=MQ==\7\27\\" .. "\27Ptmux;\27\27]1337;SetUserVar=llembas_ide=\7\27\\", vim.inspect(err))
|
||||
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "plain", LLEMBAS_TERM = "1" }))
|
||||
check("user var: a plugin set up without keys or bars says nothing, in that terminal either", err == "", vim.inspect(err))
|
||||
r = step(dir_c, "chords", { LLEMBAS_TERM = "1" })
|
||||
check("chords: in the LLeMbas terminal the bar shows the chords from the start", r.chords == true and r.guess == true, r)
|
||||
r = step(dir_c, "chords", { TMUX = "/tmp/tmux-1/default,1,0", KITTY_WINDOW_ID = "1" })
|
||||
check("chords: behind a multiplexer they are not assumed", r.guess == false, r)
|
||||
r = step(dir_c, "chords", { KITTY_WINDOW_ID = "1" })
|
||||
check("chords: a terminal known to report them is taken at its word", r.guess == true, r)
|
||||
end
|
||||
|
||||
|
||||
vim.schedule(function()
|
||||
local ok, err = xpcall(run, debug.traceback)
|
||||
if not ok then
|
||||
failed = failed + 1
|
||||
say("FAIL the checks themselves stopped: " .. tostring(err))
|
||||
end
|
||||
local leftover = vim.fn.execute("messages")
|
||||
if leftover:match("E%d+:") then
|
||||
failed = failed + 1
|
||||
say("FAIL an error message was left: " .. leftover)
|
||||
end
|
||||
say(("RAN %d, failed %d (layout)"):format(ran, failed))
|
||||
pcall(function() require("llembas").restart(true) end)
|
||||
vim.cmd("cd /")
|
||||
if own_work then vim.fn.delete(work, "rf") end
|
||||
vim.cmd(failed == 0 and "qall!" or "cquit!")
|
||||
end)
|
||||
+28
-1
@@ -1,6 +1,33 @@
|
||||
#!/bin/sh
|
||||
# The Neovim plugin's tests: headless, against the stand-in agent (tests/fake_agent.py) and, when its
|
||||
# source is at hand, the LLeMbas CLI itself. Needs nvim 0.10+ and python3.
|
||||
#
|
||||
# scripts/test-nvim.sh both suites
|
||||
# scripts/test-nvim.sh plugin the plugin on its own: chat, rewrite, suggestions, sign-in
|
||||
# scripts/test-nvim.sh layout the bars: top, bottom, tree, right bar, keys, what is remembered
|
||||
#
|
||||
# Nothing of this machine's own Neovim is read or written: the state, data, cache and configuration
|
||||
# directories are temporary ones, removed on every way out.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua
|
||||
WORK="$(mktemp -d "${TMPDIR:-/tmp}/llembas-nvim-test.XXXXXX")"
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
mkdir -p "$WORK/state" "$WORK/data" "$WORK/cache" "$WORK/config"
|
||||
export XDG_STATE_HOME="$WORK/state" XDG_DATA_HOME="$WORK/data" XDG_CACHE_HOME="$WORK/cache" XDG_CONFIG_HOME="$WORK/config"
|
||||
export LLEMBAS_NVIM_TEST_WORK="$WORK"
|
||||
# The terminal these tests run in says nothing about itself to the plugin.
|
||||
unset LLEMBAS_TERM LLEMBAS_TTY TMUX STY ZELLIJ KITTY_WINDOW_ID GHOSTTY_RESOURCES_DIR TERM_PROGRAM
|
||||
export TERM=dumb
|
||||
|
||||
which="${1:-all}"
|
||||
status=0
|
||||
if [ "$which" = all ] || [ "$which" = plugin ]; then
|
||||
nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua || status=$?
|
||||
fi
|
||||
if [ "$which" = all ] || [ "$which" = layout ]; then
|
||||
# With a screen (no -l): the bars are read from what is drawn.
|
||||
nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -c "luafile nvim/tests/layout.lua" || status=$?
|
||||
fi
|
||||
exit "$status"
|
||||
Reference in new issue
Block a user