diff --git a/README.md b/README.md index 41a6567..7dc2bb0 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,8 @@ and global (shared across projects, saved to disk). Switch between them with - **Global notes** — persisted across projects (`stdpath("data")/scratch.nvim/global.md`). - Cycle between note types with `Tab` / `S-Tab`. - Notes auto-save on close, type switch, and `VimLeavePre`. +- An empty note keeps no file on disk: the file appears once the note has + content and is removed when the note is cleared. - Configurable window size, border, title, and behavior. ## Installation diff --git a/lua/scratch/init.lua b/lua/scratch/init.lua index 2c52cb7..a7f89cd 100644 --- a/lua/scratch/init.lua +++ b/lua/scratch/init.lua @@ -85,6 +85,18 @@ local function load_file(bufnr, path) end end +--- Check whether the note holds nothing but blank lines +---@param lines string[] +---@return boolean +local function is_blank(lines) + for _, line in ipairs(lines) do + if not line:match("^%s*$") then + return false + end + end + return true +end + --- Save buffer contents to a file ---@param bufnr number ---@param path string @@ -92,11 +104,18 @@ local function save_file(bufnr, path) if not vim.api.nvim_buf_is_valid(bufnr) then return end + local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) + -- An empty note leaves no file behind; a cleared one takes its file with it + if is_blank(lines) then + if vim.fn.filereadable(path) == 1 then + vim.fn.delete(path) + end + return + end local dir = vim.fn.fnamemodify(path, ":h") if vim.fn.isdirectory(dir) == 0 then vim.fn.mkdir(dir, "p") end - local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) vim.fn.writefile(lines, path) end