0

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

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

(defun insert-numbered-chapter-headings ()
  "Insert **** 第x章 at cursor point."
  (interactive)
  (insert (format "**** 第%s章"
          n))
  (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:")
Drew
  • 77,472
  • 10
  • 114
  • 243
Sati
  • 775
  • 6
  • 23

1 Answers1

2

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

(defvar my-counter nil
  "Doc-string.")
(make-variable-buffer-local 'my-counter)

(defun reset-counter ()
"Doc-string."
  (interactive)
  (let ((temporary-number (read-number "NUMBER:  " 1)))
    (setq my-counter temporary-number)))
lawlist
  • 19,106
  • 5
  • 38
  • 120
  • The function doesn't pair well with insert-numbered-chapter-headings. Value of n remains unchanged after calling reset-counter. – Sati Aug 24 '19 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 '19 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 '19 at 16:40