Search code examples
elisp

Numerate the org headings


I want to numerate the org-headings from:

* heading how
* heading are
* heading you

to

* 1.heading how
* 2.heading are
* 3.heading you

So I compose a numerate-org-heading as:

(defun numerate-org-heading (args)
  "Numerate org headings"
  (interactive "s")
  (let ((count 0))
    (while (re-search-forward args nil t)
      (setq count (1+ count))
      (replace-match (concat "\1" (string count)
                             (forward-char 1))))))

Unfortunately, It report error of Wrong type argument: stringp, ^* when i call numerate-org-heading interactively and feed it with string "^*".

Could you please give any hints to solve the problem?


Modified the function and it works now for particular cases:

(defun numerate-org-heading (args)
  "Numerate org headings"
  (interactive "s")
  (let ((count 0))
    (while (re-search-forward args nil t)
      (setq count (1+ count))
      (replace-match (concat "* " (number-to-string count) ".")
                     (forward-char 1))))))

Solution

  • If you set args as a matching group and capture any trailing space, you can replace that back as group 1 ("\\1") followed by your numeration e.g. 1.

    (defun numerate-org-heading (args)
      "Numerate org headings"
      (interactive "s")
      (let ((count 0))
        (while (re-search-forward (concat "\\(" args "[ \\t]*\\)") nil t)
          (setq count (1+ count))
          (replace-match (concat "\\1" (number-to-string count) ".")))))