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?
4 Answers
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 fromemacs -Q
to be sure that works)RET
RET
and it will create the directory without any further prompting. Sep 29, 2014 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
.– DrewSep 29, 2014 at 14:31
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
m
ake new dir?). Hit RET. - Continue with typing the new file name that you want to create in that new dir. Hit RET.
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.
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: