2016-07-25 Making directories on the fly

Today, a friend asked me how to create a directory – or a hierarchy of them – while finding a file in a nonexistent directory. I found some clues on the ‘net, but the best one used the old advice mechanism. So I decided to do it myself, based on the hints found. It turned out to be simpler than I thought; it’s made even easier by the fact that Elisp’s make-directory function acts basically like mkdir -p when given non-nil second (optional) argument.

(defun make-parent-directory ()
  "Make sure the directory of `buffer-file-name' exists."
  (make-directory (file-name-directory buffer-file-name) t))

(add-hook 'find-file-not-found-functions #'make-parent-directory)

Read the manual and/or relevant docstrings for the descriptions of the functions used. Note that (under normal conditions – see its source code) make-directory always returns nil, so if there are any other functions in the find-file-not-found-functions hook, they should also be executed.

Happy mkdir-ing!

CategoryEnglish, CategoryBlog, CategoryEmacs