From 70420a474c0e0ea6f3e08f346182921801ebb2d6 Mon Sep 17 00:00:00 2001 From: "Andrey A. Ugolnik" Date: Sat, 5 Sep 2026 18:26:45 +0200 Subject: [PATCH] fix(notes): keep no file on disk for an empty note Opening a persistent note was enough to create its file: the save path wrote the buffer unconditionally, so an untouched Local note left a stray .scratch.md in the project (and a global.md plus its directory in stdpath("data")). Clearing a note left the file behind as an empty one. Write the file only when the note has content, and delete an existing file when the note holds nothing but blank lines. --- README.md | 2 ++ lua/scratch/init.lua | 21 ++++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) 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