Scratchpad utilities
| 1 | local M = {} |
| 2 | |
| 3 | |
| 4 | M.files = {} |
| 5 | local cwd = vim.fn.getcwd() |
| 6 | M.hash = vim.fn.sha256(cwd) |
| 7 | M.scratchdir = vim.fn.stdpath("data") .. "/scratch" |
| 8 | if vim.fn.isdirectory(M.scratchdir) == 0 then |
| 9 | vim.fn.mkdir(M.scratchdir, "p") |
| 10 | return |
| 11 | end |
| 12 | end |
| 13 | |
| 14 | ---Gets the name of the file that lives in the scratch directory |
| 15 | ---@param ext string The file extension |
| 16 | ---@return string |
| 17 | |
| 18 | return M.scratchdir .. "/" .. M.hash .. "." .. ext |
| 19 | end |
| 20 | |
| 21 | ---Opens a buffer for the given file extension |
| 22 | ---@param ext string? |
| 23 | |
| 24 | if not ext then |
| 25 | ext = vim.fn.expand("%:e") |
| 26 | end |
| 27 | -- open scratch for the ext |
| 28 | local filename = M.getfile(ext) |
| 29 | local buf = vim.api.nvim_create_buf(false, false) |
| 30 | |
| 31 | -- immediately move into floating window |
| 32 | local width = math.floor(vim.o.columns * 0.8) |
| 33 | local height = math.floor(vim.o.lines * 0.8) |
| 34 | local row = math.floor((vim.o.lines - height) / 2) |
| 35 | local col = math.floor((vim.o.columns - width) / 2) |
| 36 | vim.api.nvim_open_win(buf, true, { |
| 37 | relative = "editor", |
| 38 | width = width, |
| 39 | height = height, |
| 40 | row = row, |
| 41 | col = col, |
| 42 | style = "minimal", |
| 43 | border = "rounded", |
| 44 | title = " " .. require("mini.icons").get("filetype", ext) .. " Scratchpad: " .. filename .. " ", |
| 45 | }) |
| 46 | vim.cmd("edit " .. filename) |
| 47 | |
| 48 | -- mark hidden |
| 49 | vim.bo[buf].bufhidden = "wipe" |
| 50 | vim.bo[buf].buflisted = false |
| 51 | |
| 52 | -- easy close |
| 53 | vim.keymap.set("n", "q", ":q<cr>", { buffer = buf, nowait = true }) |
| 54 | vim.keymap.set("n", "<C-c>", "<Esc>:q<cr>", { buffer = buf, nowait = true }) |
| 55 | |
| 56 | -- execute on save |
| 57 | vim.api.nvim_create_autocmd("BufWritePost", { |
| 58 | buffer = buf, |
| 59 | callback = function() |
| 60 | vim.cmd("luafile %") |
| 61 | end, |
| 62 | }) |
| 63 | end |
| 64 | |
| 65 | return M |