Org-Mode Count the Number of Headings in a Region

Sometimes I want to see how many headings are in an org-mode file I’m working in. For example, I like to know the number of items I have to refile.

This function will count the headings in a marked region:

(defun count-headings-in-region (start end)
  "Count the number of level 1 headings in the region."
  (interactive "r")
  (save-excursion
    (save-restriction
      (narrow-to-region start end)
      (goto-char (point-min))
      (let ((count 0))
        (while (re-search-forward "^\\* " nil t)
          (setq count (1+ count)))
        (message "Number of level 1 headings: %d" count)))))

This code was generated using ChatGPT with Emacs.