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

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."
  ;; Widen buffer temporarily as narrowing would affect the exporting.
     ;; Loop through each headline.
      (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))
          ;; 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)
      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
  • 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.