9

When opening a new file whose parent directory doesn't exist yet, I either open a shell window, or an Emacs shell buffer, and then mkdir the directory in it. I find this cumbersome. Is there an easier way?

15

You don't need to do that, if that's your question.

C-x C-f /some/new/directory/newfile.txt

Emacs prints a message to let you know that the directory /some/new/directory/ does not yet exist: Use M-x make-directory RET RET to create the directory and its parents.

Insert text into the new buffer for new file newfile.txt.

C-x C-s to save the file.

Emacs asks you whether you want to create the missing intermediate directories (e.g., new/directory/. You hit y for "yes".

Not very cumbersome, IMO. The UI needs to ask you for confirmation, because you could easily have mistyped the name of an existing directory.

  • You can also just use M-x make-dir tab (tested from emacs -Q to be sure that works) RET RET and it will create the directory without any further prompting. – Jonathan Leech-Pepin Sep 29 '14 at 12:13
  • 1
    @JonathanLeech-Pepin: Yes, of course. (That's what the message says.) But if you have already opened the new file buffer, just try to save it and confirm dir creation with y. – Drew Sep 29 '14 at 14:31
7

For ido users

  • Do C-x C-f (which should call ido-find-file) and enter a non-existent path.
  • Press M-m (mnemonic for make new dir?). Hit RET.
  • Continue with typing the new file name that you want to create in that new dir. Hit RET.
1

When in this situation, emacs should have told you something like:

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

Is it cumbersome?

I'll say, yes it is.

0

If you really want to make find-file to automatically create parent directories when not already exists, you can do the following in your init file.

(defun my-find-file (orig-fun &rest args)
  (let* ((filename (car args))
         (directory (file-name-directory filename)))
    (if (not (file-directory-p directory))
        (make-directory directory t))
    (apply orig-fun args)))

(advice-add 'find-file :around 'my-find-file)

After all, Emacs was designed to be extensible and customizable.

Reference:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.