In Emacs, an interactive function is also known as a command. A command can be invoked from M-x.

To make a function interactive (i.e. to turn it into a command which can be used with M-x or bound to keybindings), you must call (interactive) at the start of the function, for example:

(defun greet ()
  (interactive)
  (print "hello"))

To prompt user for arguments, call (interactive) with a string argument (the arg-descriptor), like so:

(interactive "P\nbGive me a buffer: ")

The substrings, delimitted by \n, tells Emacs how to obtain each argument. Each substring main contain a code letter and typically a prompt.

Code letters

  • P: Get the prefix argument. No prompt string necessary.
  • b: Prompt for a buffer name.
  • s: Prompt for a string.
  • c: Promp for a character
  • *: If present at the beginning of string, an error will be signaled if the current buffer is read-only.
  • @: If present at the beginning of string, and mouse events were used to invoke the command, then the window associated with these events will be selected before it is run.
  • ^: if present at the beginning of string, and the command was invoked shift-translation, set the mark and activate the region temporarily, or extend an already active region, before the command is run. If the command was invoked without shift-translation, and the region is temporarily active, deactivate the region before the command is run.

Prompt String

The prompt string is formatted through format-message (Manual); use placeholders (e.g. %s) to include previous argument values, starting with the first one.

Prompt for arguments

You do not have pass these strings to prompt for arguments. Instead, you can do so with your own code, like so:

; ...
(interactive
 (let ((string (read-string "Foo: " nil 'my-history)))
   (list (region-beginning) (region-end) string)))
; ...