local M = {} local config = require('chatgpt_nvim.config') local conf = config.load() local debug_bufnr = nil if conf.improved_debug then 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 lines = { "Delete lines for directories you do NOT want, then :wq" } for _, d in ipairs(dirs) do table.insert(lines, d) 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 = on_write }) 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 -- 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 = {} local current_chunk = {} local current_text = "" for _, line in ipairs(lines) do 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 end end if current_text ~= "" then table.insert(chunks, current_text) end return chunks end return M