I have a command that semi-automates the insertion of numbered chapter headings in an org-mode file.

(defun reset-counter ()
  (setq n 1))

(defun insert-numbered-chapter-headings ()
  "Insert **** 第x章 at cursor point."
  (insert (format "**** 第%s章"
  (setq n (+ n 1)))

(define-key org-mode-map (kbd "<S-return>") 'insert-numbered-chapter-headings)
(define-key org-mode-map (kbd "C-c C-x r") 'reset-counter)

Currently, reset-counter just sets variable n back to 1.

How do I modify the function so that I can be prompted to enter any number other than 1, with 1 as the default when left blank?

(message "String is %s" (read-char "Enter number:")
  • Can this be done with a if-else statement?
    – Sati
    Aug 24, 2019 at 16:25

1 Answer 1


The function read-number has an optional argument for the default value. Here is an example:

(defvar my-counter nil
(make-variable-buffer-local 'my-counter)

(defun reset-counter ()
  (let ((temporary-number (read-number "NUMBER:  " 1)))
    (setq my-counter temporary-number)))
  • The function doesn't pair well with insert-numbered-chapter-headings. Value of n remains unchanged after calling reset-counter.
    – Sati
    Aug 24, 2019 at 16:32
  • 1
    In the example, I am not setting n -- I am setting my-counter instead. You did not define n in your example as a global or buffer-local variable and I wished to avoid any confusion you may have had in that regard. In this example, I let-bound n locally for only the duration of the function. As such, it will not modify n if you have that as a buffer-local or global variable. I would suggest using unique names for buffer-local or global variables, and I would also suggest that you define them specifically instead of just creating them with setq -- that way you can visit the code.
    – lawlist
    Aug 24, 2019 at 16:35
  • 1
    I changed the n to temporary-number to avoid further confusion; and, I added a doc-string to the defvar statement so that we can look it up with M-x describe-variable and/or M-x find-variable.
    – lawlist
    Aug 24, 2019 at 16:40

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.