emacs interactive function with optional numeric prefix
Asked Answered
P

1

8

How do I specify a function which has optional numeric prefix, if not, it prompts for a number? basically how goto-line behaves?

(defun my-function(&optional  n)
  ; I have tried
  (interactive "N") ; reads string, no prompt
  (interactive "p") ; defaults to one
  (interactive (if (not n) (read-number "N: "))) ; runtime error

so how do I make work? thanks

Printmaking answered 7/2, 2010 at 0:10 Comment(1)
FWIW, if you want a prompt for "N", just add the prompt text after the N; (interactive "NType a number: ").Aldis
G
9

Take a look at how 'goto-line is defined (M-x find-function goto-line RET).

(defun my-function (n)
  "Example function taking a prefix arg, or reading a number if no prefix arg"
  (interactive
   (if (and current-prefix-arg (not (consp current-prefix-arg)))
       (list (prefix-numeric-value current-prefix-arg))
     (list (read-number "N: ")))))
Garofalo answered 7/2, 2010 at 0:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.