I'm trying to export an org file into a file that contains only the visible entries (and parents) of a sparse tree (matching a specific tag).

For example, applying this to the following tree

* A
  Some content at level 0
** A1 :matchthis:
   Some content at level 1
** A2
* B
  Some content at level 0

matching the tag matchthis should produce the same result as exporting the tree:

* A
  Some content at level 0
** A1 :matchthis:
   Some content at level 1

If I export everything (in PDF, or txt), then the top level headlines (B) are also visible and therefore always included.

I don't see a way to export an org-file to an org-file with only the matched entries, which could be an acceptable intermediate step.


As the built-int sparse tree has some limitations I've made a custom sparse tree function. I think with this function you can do what you want.

First it makes the sparse tree, then it hides everything (this is needed as the sparse tree function calls org-overview which reveals all level 1 headings) to reveal only the matches and the parents. You can optionally also show the body of the matches and/or the parents.

For your example

  • call it with (my-org-custom-sparse-tree nil "matchthis" t t) to create the sparse tree
  • and then use (org-org-export-as-org nil nil t t) to export the visible part to an org buffer.
(defun my-org-custom-sparse-tree (todo-only match &optional
                                            match-body parents-body)
  "Create a custom sparse tree that only shows matched headings and parents.
For TODO-ONLY and MATCH see `org-match-sparse-tree'.
If MATCH-BODY is non-nil the bodies of the matches are shown.
If PARENTS-BODY is non-nil the bodies of the parents are shown."
  ;; Create the sparse tree.
  (org-match-sparse-tree todo-only match)
  (let ((pt-first (save-excursion
        (hls org-occur-highlights))
    ;; Hide everything.
    (outline-flag-region pt-first (point-max) t)
    ;; For each occur highlight overlay (the matches).
    (dolist (hl hls)
        (goto-char (overlay-start hl))
        ;; Unhide match.
        (when match-body (outline-show-entry))
        ;; Unhide parents.
        (while (org-up-heading-safe)
          (when parents-body (outline-show-entry))))))
  ;; Hide all archived subtrees again.
  (org-hide-archived-subtrees (point-min) (point-max)))

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.