local M = {} local config = require('chatgpt_nvim.config') local conf = config.load() local prompts = require('chatgpt_nvim.prompts') 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") end function M.debug_log(msg) if conf.improved_debug and debug_bufnr then vim.api.nvim_buf_set_lines(debug_bufnr, -1, -1, false, { msg }) else if conf.debug then vim.api.nvim_out_write("[chatgpt_nvim:debug] " .. msg .. "\n") end end end function M.pick_directories(dirs) local selected_dirs = {} local selection_instructions = prompts["file-selection-instructions"] local lines = { selection_instructions } 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") vim.api.nvim_buf_set_option(bufnr, "bufhidden", "wipe") vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines) local function on_write() local new_lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) local final_dirs = {} for _, l in ipairs(new_lines) do if l ~= "" and not l:match("^Delete lines") and not l:match("^#") then table.insert(final_dirs, l) end end selected_dirs = final_dirs vim.api.nvim_buf_set_option(bufnr, "modified", false) end vim.api.nvim_create_autocmd("BufWriteCmd", { buffer = bufnr, once = true, callback = function() on_write() -- Automatically close the buffer once saved vim.cmd("bd! " .. bufnr) end }) vim.cmd("split") vim.cmd("buffer " .. bufnr) -- Wait up to 30s for user to close vim.wait(30000, function() local winids = vim.api.nvim_tabpage_list_wins(0) for _, w in ipairs(winids) do local b = vim.api.nvim_win_get_buf(w) if b == bufnr then return false end end return true end) return selected_dirs end return M