-- Scratchpad buffers for ad-hoc text editing and quick lookups. -- -- Two kinds of scratch: -- * plain in-memory buffer (no filetype, no LSP) -- * temp-file scratch with a chosen filetype (gets LSP via AstroNvim AstroFile) -- -- LSP requires a real file, because AstroNvim skips its LSP attach for -- buftype=nofile buffers. Temp files live in the nvim cache dir, so they -- never pollute the project. local M = {} local cache_dir = vim.fn.stdpath "cache" .. "/scratch" --- Return the next free scratch index, based on existing buffers named scratch-. local function next_index() local max = 0 for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do local num = (vim.fn.bufname(bufnr) or ""):match "scratch%-(%d+)" if num and tonumber(num) > max then max = tonumber(num) end end return max + 1 end --- Open a plain in-memory scratch buffer. local function open_plain(index) local buf = vim.api.nvim_create_buf(true, true) vim.api.nvim_buf_set_name(buf, "scratch-" .. index) vim.bo[buf].buftype = "nofile" vim.bo[buf].bufhidden = "hide" vim.bo[buf].swapfile = false vim.bo[buf].buflisted = true vim.api.nvim_win_set_buf(0, buf) end --- Open a temp-file scratch with the given filetype so that LSP attaches. local function open_file(index, filetype) local safe_ft = filetype:gsub("[^%w_%-]", "") vim.fn.mkdir(cache_dir, "p") local path = cache_dir .. "/scratch-" .. index .. "." .. safe_ft vim.fn.writefile({}, path) vim.cmd.edit(path) end --- Open a scratch buffer. When `filetype` is set, a temp file is used so the --- matching LSP server attaches; otherwise an in-memory buffer is opened. ---@param filetype? string function M.open(filetype) local index = next_index() if filetype and filetype ~= "" then open_file(index, filetype) else open_plain(index) end end --- Prompt for a scratch filetype, then open the scratch. function M.open_prompt() vim.ui.input({ prompt = "Scratch filetype (empty = plain text, e.g. json/markdown/go): ", }, function(input) if input == nil then return end M.open(input) end) end return M