133 lines
2.5 KiB
Lua
133 lines
2.5 KiB
Lua
if not pcall(require, "nui.layout") then
|
|
vim.notify("nui.nvim not installed!", vim.log.levels.ERROR)
|
|
return
|
|
end
|
|
|
|
local M = {}
|
|
|
|
local opts = require("anthropic").opts
|
|
local layout = require("nui.layout")
|
|
local popup = require("nui.popup")
|
|
|
|
M.components = {
|
|
history = popup({
|
|
border = {
|
|
style = opts.border_style,
|
|
},
|
|
enter = false,
|
|
}),
|
|
input = popup({
|
|
border = {
|
|
style = opts.border_style,
|
|
},
|
|
enter = true,
|
|
})
|
|
}
|
|
|
|
M.box = layout(
|
|
{
|
|
relative = "editor",
|
|
position = {
|
|
row = "50%",
|
|
col = "50%",
|
|
},
|
|
size = {
|
|
width = "80%",
|
|
height = "90%",
|
|
},
|
|
},
|
|
layout.Box(
|
|
{
|
|
layout.Box(M.components.history, { size = "70%" }),
|
|
layout.Box(M.components.input, { size = "30%" })
|
|
},
|
|
{ dir = "col" }
|
|
)
|
|
)
|
|
|
|
M.active = false
|
|
M.initialized = false
|
|
M.cursor_y = 0
|
|
M.cursor_x = 0
|
|
|
|
--- # Set up the chat window
|
|
---
|
|
--- Adds autocommands and mounts the chat window
|
|
local function initialize()
|
|
if M.initialized then
|
|
return
|
|
end
|
|
|
|
M.box:mount()
|
|
|
|
-- autohide chat when leaving the chat buffer
|
|
for _, p in pairs(M.components) do
|
|
p:on("BufLeave", function()
|
|
vim.schedule(function()
|
|
local buf = vim.api.nvim_get_current_buf()
|
|
for _, q in pairs(M.components) do
|
|
if q.bufnr == buf then
|
|
return
|
|
end
|
|
end
|
|
M.box:hide()
|
|
end)
|
|
end)
|
|
end
|
|
|
|
-- automatically resize the chat window on SIGWINCH
|
|
vim.api.nvim_create_autocmd("WinResized", {
|
|
group = vim.api.nvim_create_augroup("refresh_anthropic_layout", { clear = true }),
|
|
callback = function()
|
|
M.box:update()
|
|
end,
|
|
})
|
|
|
|
M.initialized = true
|
|
end
|
|
|
|
--- # Open the chat window
|
|
function M.open()
|
|
initialize()
|
|
M.box:show()
|
|
M.active = true
|
|
end
|
|
|
|
--- # Close the chat window
|
|
function M.close()
|
|
M.box:hide()
|
|
M.active = false
|
|
end
|
|
|
|
--- # Toggle the chat window
|
|
function M.toggle()
|
|
if M.active then
|
|
M.close()
|
|
else
|
|
M.open()
|
|
end
|
|
end
|
|
|
|
--- # Write text to the chat window
|
|
---
|
|
--- Writing out of the buffer's bounds will cause an error!
|
|
---@param text string[] # Each element is a line of text
|
|
---@param row integer? # Defaults to last row written to
|
|
---@param col integer? # Defaults to last col written to + 1
|
|
function M.write(text, row, col)
|
|
col = col or M.cursor_x
|
|
row = row or M.cursor_y
|
|
|
|
local buf = M.components.history.bufnr
|
|
|
|
vim.api.nvim_buf_set_text(buf, row, col, row, col, text)
|
|
|
|
M.cursor_y = M.cursor_y + #text - 1
|
|
if #text > 1 then
|
|
M.cursor_x = 0
|
|
end
|
|
M.cursor_x = M.cursor_x + #text[#text]
|
|
end
|
|
|
|
return M
|