Can I create directories that don't exist while creating a new file in emacs?

You can also advise function find-file to transparently create necessary directories.

(defadvice find-file (before make-directory-maybe (filename &optional wildcards) activate)
  "Create parent directory if not exists while visiting file."
  (unless (file-exists-p filename)
    (let ((dir (file-name-directory filename)))
      (unless (file-exists-p dir)
        (make-directory dir t)))))

Simply put this in your .emacs somewhere and use C-x C-f as usual.


When I supply a pathname with a nonexistent component, find-file (i.e. C-x C-f), gives me an extra message that says

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

Since the file is not created until you first save the buffer, you can either run make-directory right after your new buffer comes up or you can do it any other time before you need to save the file. Then from the buffer that needs a directory, type M-x make-directory RET RET (it will prompt for the directory to create (the default is derived from the buffer's pathname); the second RET is to accept the default).


The Ido mode provides ido-find-file that is a replacement of find-file and gives you much more features. For instance, it allows you to create new directory meanwhile you open the file.

  • Type C-x C-f as usual (which is remapped to ido-find-file),

  • provide the non-existent path,

  • press M-m which will prompt for the new directory to create,

  • and then specify the file name to visit in the newly created directory.

Tags:

Emacs