Make parent directory if it doesn't exist when saving a file in Emacs

Sometimes I create a buffer by navigating into a directory that doesn't exist. For example, I create a brand new project (an empty dir), then navigate into <project_dir>/lib/<project_name>.rb. Emacs happily allows me to do this because buffers don't necessarily need to be bound to an actual file, so no problem there.

The problem comes when I try to save. As the lib directory doesn't exist, I get an error.

The solution

The way to solve this is to write an elisp function to create the (in this case) lib directory.

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

And then add a hook to call this function in case the file (or directory in this case) does not exist.

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

This little trick has saved me a lot of frustration and I hope it does the same for you.