2

I want to create the directory tree structure like this out of org-mode outlines.

Dir1

  • Dir-1.1
    • Dir -1.1.1
  • Dir-1.2

Dir 2

  • Dir-2.1
  • Dir-2.2

I am new to emacs and I have tried a few shell commands from here like

  xargs -d '\n' mkdir -p -- < test.txt 

For that to work I need a file with the following structure.

# Test.txt
A1/A2/A3
B1/B2/B3
C1/C2/C3

TLDR: Generate Directory structure out of org outlines.

2

org-element-parse-buffer and org-element-map are your friends. You get the doc strings of these two functions (and of every other function) by C-h f.

The following function org-headlines-to-dir-tree parses the org buffer via org-element-parse-buffer and creates the directories corresponding to the headlines via org-element-map. This is pure Elisp. No shell commands are required.

(defun org-headlines-to-dir-tree (dir &optional data)
  "Transform org headlines in DATA to directory tree below DIR.
DATA defaults to the headline structure of the current org buffer."
  (interactive "DTarget directory:")
  (unless data
    (unless (derived-mode-p 'org-mode)
      (user-error "%S is not an org buffer" (current-buffer)))
    (setq data (org-element-parse-buffer 'headline)))
  (unless (file-directory-p dir)
    (user-error "%S is not a directory" dir))
  (let ((default-directory (expand-file-name dir)))
    (org-element-map
        data
        'headline
      (lambda (el)
        (let ((title (org-element-property :title el))
              (contents (org-element-contents el)))
          (when (y-or-n-p (format "Create directory %S?" (expand-file-name title)))
            (mkdir title)
            (when contents
              (org-headlines-to-dir-tree title contents))))) ;; Recursion.
      nil ;; info
      nil ;; first match
      'headline ;; no-recursion (We do the recursion ourselves with additional directory changes.)
      )))

You can paste that stuff into your *scratch* buffer and evaluate it by placing point in to the function body and typing C-M-x.

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.