Adobe
Adobe

Reputation: 13477

How to make Emacs create intermediate dirs - when saving a file?

Is there a way to create folder tree in emacs - similar to

mkdir -p

in bash?

Basically - I want emacs to create all the intemediate dirs - if they were not existing - when I save a file.

Upvotes: 18

Views: 3500

Answers (3)

Victor Deryagin
Victor Deryagin

Reputation: 12225

Function make-directory does that. Your particular problem may be solved like this:

(add-hook 'before-save-hook
          (lambda ()
            (when buffer-file-name
              (let ((dir (file-name-directory buffer-file-name)))
                (when (and (not (file-exists-p dir))
                           (y-or-n-p (format "Directory %s does not exist. Create it?" dir)))
                  (make-directory dir t))))))

Upvotes: 29

Hunter McMillen
Hunter McMillen

Reputation: 61510

You can also just execute mkdir -p from inside emacs using M-! to get a shell command prompt.

Then all you have to do is put your directory structure in:

M-! dir1/dir2/dir3/dir4.....

Upvotes: 3

atlau
atlau

Reputation: 971

(make-directory DIR &optional PARENTS)

Create the directory DIR and any nonexistent parent dirs. If DIR already exists as a directory, signal an error, unless PARENTS is set.

Upvotes: 2

Related Questions