Skip to content

[idea] Auto-create parent directories on BufWritePre #288

Description

@stanfish06

What

Add a BufWritePre autocmd that creates any missing parent directories before saving, so :e some/new/path/file.lua followed by :w succeeds instead of erroring with E212: Can't open file for writing.

Where

lua/config/options.lua — near the other BufWritePre logic, or as a new autocmd group.

Why it matters

The current config already edits files via :e **/* wildcards (<leader>e) and opens new buffers with <leader>bn. It's a common workflow to open a new file inside a directory that doesn't exist yet, especially when sketching out new module structures. Without this autocmd, every such save requires a manual !mkdir -p %:h first.

Recommended implementation

vim.api.nvim_create_autocmd("BufWritePre", {
    group = vim.api.nvim_create_augroup("AutoMkdir", { clear = true }),
    callback = function(ev)
        if ev.match:match("^%a+://") then return end  -- skip remote/oil buffers
        local dir = vim.fn.fnamemodify(ev.match, ":p:h")
        if vim.fn.isdirectory(dir) == 0 then
            vim.fn.mkdir(dir, "p")
        end
    end,
})

The %a+:// guard prevents it from running on oil://, fugitive://, or other virtual buffers whose names look like paths but aren't.

This pairs naturally with the existing BufWritePre formatting autocmd in plugin_config.lua (lines 190–196).

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions