fix: buffer handling

This commit is contained in:
2024-12-29 16:39:58 +01:00
parent 40c9d5672d
commit 162ab2d820
3 changed files with 61 additions and 26 deletions

View File

@@ -4,6 +4,14 @@ local conf = config.load()
local debug_bufnr = nil
if conf.improved_debug then
-- Check if a debug buffer is already open. Close it first to avoid duplicates.
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
local name = vim.api.nvim_buf_get_name(buf)
if name == "ChatGPT_Debug_Log" then
vim.api.nvim_buf_delete(buf, {force = true})
end
end
debug_bufnr = vim.api.nvim_create_buf(false, true)
vim.api.nvim_buf_set_name(debug_bufnr, "ChatGPT_Debug_Log")
vim.api.nvim_buf_set_option(debug_bufnr, "filetype", "log")
@@ -21,11 +29,19 @@ end
function M.pick_directories(dirs)
local selected_dirs = {}
local lines = { "Delete lines for directories you do NOT want, then :wq" }
local lines = { "Delete lines for directories you do NOT want, then save & close (e.g. :wq, :x, or :bd)" }
for _, d in ipairs(dirs) do
table.insert(lines, d)
end
-- If a file selection buffer is already open, close it to avoid confusion
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
local name = vim.api.nvim_buf_get_name(buf)
if name:match("ChatGPT_File_Selection") then
vim.api.nvim_buf_delete(buf, {force = true})
end
end
local bufnr = vim.api.nvim_create_buf(false, false)
vim.api.nvim_buf_set_name(bufnr, "ChatGPT_File_Selection")
vim.api.nvim_buf_set_option(bufnr, "filetype", "markdown")
@@ -47,7 +63,11 @@ function M.pick_directories(dirs)
vim.api.nvim_create_autocmd("BufWriteCmd", {
buffer = bufnr,
once = true,
callback = on_write
callback = function()
on_write()
-- Automatically close the buffer once saved
vim.cmd("bd! " .. bufnr)
end
})
vim.cmd("split")
@@ -68,8 +88,6 @@ function M.pick_directories(dirs)
return selected_dirs
end
-- A function to chunk a long string if it exceeds token_limit
-- We'll just do rough splits by lines or paragraphs.
function M.chunkify(text, estimate_tokens_fn, token_limit)
local lines = vim.split(text, "\n")
local chunks = {}
@@ -80,9 +98,7 @@ function M.chunkify(text, estimate_tokens_fn, token_limit)
local test_text = (current_text == "") and line or (current_text .. "\n" .. line)
local est_tokens = estimate_tokens_fn(test_text)
if est_tokens > token_limit then
-- push current chunk
table.insert(chunks, current_text)
-- start a new chunk
current_text = line
else
current_text = test_text
@@ -96,4 +112,4 @@ function M.chunkify(text, estimate_tokens_fn, token_limit)
return chunks
end
return M
return M