Emacs: Create directory before saving

Creating a new file in Emacs is as easy as opening it. If you ask Emacs to open a file which doesn’t exist, it won’t complain; It will open up a blank buffer pointing at it. It will even let you open a file in a directory that doesn’t exist (yet).

If you do this, Emacs will let you know, by displaying this message:

Use M-x make-directory RET RET to create the directory and its parents

Which is handy… but wouldn’t it be nice if we didn’t even have to do that? This being Emacs, we don’t.

(add-hook 'before-save-hook
          '(lambda ()
             (or (file-exists-p (file-name-directory buffer-file-name))
                 (make-directory (file-name-directory buffer-file-name) t))))

If you add that to your .emacs, you won’t have to. When you save your buffer, Emacs will check to see if the path exists. If it doesn’t, it will create it for you, including any parent directories.

2008/12/11
Previously On Atomized:

Discussion

That’s a good one, that probably belongs on the Emacs Wiki, if it isn’t there already.

I suppose the only problem is if a typo had made the new directory. That’s avoidable as long as you pay attention for the message “Use M-x make-directory RET RET to create the directory and its parents”

aaron
2008/12/11

This should really be the default behavior of emacs. If you start a file in a directory which doesn’t exist yet, then you can’t use M-! mkdir new/dir (and can’t start a new M-x shell either) because the shell needs the directory to be there. At the same time, the message in the minibuffer can be obscured by other hooks, making it invisible. So this doesn’t just belong to the Wiki — this should be in every .emacs file!
Thanks

andrew
2010/04/25

Participate