0

I want to be able to create a function that splits or exports every single headline in a org mode file (recursively) into a separate file.

Ideally that would be a .md file but I can also live with a .org file

Does anyone have any examples on how to achieve this? Previous answers found here/org forums were focused only on top level headers and had issues with looping over the file.

to illustrate this org file:

* Title of Heading 1
  Text 1

** Sub-Heading 2
   Text 2

* Title of Heading 2
  Text 3

would result in the files

Title of Heading 1.md
Sub-Heading 2.md
Title for Heading 2.md
4

If a region is active org-md-export-as-markdown exports the region only.

So we have to

  • loop through each headline
  • set the active region
  • export the region to a markdown buffer
  • and finally use the title to save it
(defun my-org-export-each-headline-to-markdown (&optional scope)
  "Export each headline to a markdown file with the title as filename.
If SCOPE is nil headlines in the current buffer are exported.
For other valid values for SCOPE see `org-map-entries'.
Already existing files are overwritten."
  (interactive)
  ;; Widen buffer temporarily as narrowing would affect the exporting.
  (org-with-wide-buffer
   (save-mark-and-excursion
     ;; Loop through each headline.
     (org-map-entries
      (lambda ()
        ;; Get the plain headline text without statistics and make filename.
        (let* ((title (car (last (org-get-outline-path t))))
               (dir (file-name-directory buffer-file-name))
               (filename (concat dir title ".md")))
          ;; Set the active region.
          (set-mark (point))
          (outline-next-preface)
          (activate-mark)
          ;; Export the region to a markdown file.
          (with-current-buffer (org-md-export-as-markdown)
            ;; Save the buffer to file and kill it.
            (write-file filename)
            (kill-current-buffer))))
      nil scope))))

Then use M-x my-org-export-each-headline-to-markdown to export the headlines of the current buffer.

You probably want to add this to the top of your org file to not get a table of contents:

#+OPTIONS: toc:nil
1
  • that’s perfect @Hubisan!
    – zeltak
    Jan 17 '20 at 14:49

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.