I want to apply (org-id-get-create) to every top-level heading in the buffer. How can I loop through all top-level org-mode headings in the current buffer?


2 Answers 2


You can use org-map-entries to apply a function to all the entries in a org-mode buffer matching a search. In this case the search "LEVEL=1" will match all top level headlines. The function you specify will be called without arguments with the point on the headline. So (org-map-entries 'org-id-get-create "LEVEL=1") will apply the org-id-get-create function to every LEVEL 1 headline.

  • 1
    Golly, the docs could be improved. "MATCH is a tags/property/todo match as it is used in the agenda tags view. Only headlines that are matched by this query will be considered during the iteration. When MATCH is nil or t, all headlines will be visited by the iteration." Why not add a cross-reference to the place where this format is actually documented? ... If, indeed, it is actually documented anywhere? Jan 12, 2021 at 11:09
  • @JoeCorneli The documentation for the query syntax is here: orgmode.org/manual/… You have to click through a lot of pages to get everything
    – erikstokes
    Jan 12, 2021 at 16:41
  • Thanks for the link! LEVEL seems specifically a bit buried! Jan 12, 2021 at 19:51

I couldn't find an built-in org function for that, the following function should solve it.

(defun adl/org-top-level-heading-cycle ()
  (if (not (search-forward-regexp "^* " nil t))
    (goto-char 1)
    (search-forward-regexp "^* " nil t))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.