Created
September 22, 2024 15:58
-
-
Save casperlehmann/a8d0ba79ce0163ee36b1b7fb71861e2a to your computer and use it in GitHub Desktop.
Neovim: Prompt for directory creation when attempting to write to a non-existing path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- Prompt for directory creation when attempting to save to non-existing location | |
| -- Create an autocommand group, clearing it of any existing commands | |
| vim.api.nvim_create_augroup('CreateMissingDir', { clear = true }) | |
| -- Setup an auto command that triggers prior to vim writing a buffer | |
| vim.api.nvim_create_autocmd('BufWritePre', { | |
| -- Specifies that the auto command belongs to the augroup we just created | |
| -- and that it applies to all file types (*) | |
| group = 'CreateMissingDir', | |
| pattern = '*', | |
| -- Define a callback for the auto command. This triggers when BufWritePre is encountered. | |
| callback = function() | |
| -- Check if current directory exists | |
| local dir = vim.fn.expand '%:h' | |
| if vim.fn.isdirectory(dir) == 0 then | |
| -- If directory does not exist, ask whether to create it | |
| local choice = vim.fn.input 'Directory does not exist. Create it? (y/n): ' | |
| if choice == 'y' then | |
| vim.fn.mkdir(dir, 'p') | |
| end | |
| end | |
| end, | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment