Yes, all Emacs commands are functions, but not all functions are Emacs commands. You can make an arbitrary elisp function a command accessible via M-x
using (interactive)
:
(defun my-command ()
"This is the docstring"
(interactive)
(do-foo)
(do-bar))
Now that you've defined my-command
as interactive, you can immediately access it with M-x my-command
. Emacs does all the bookkeeping with the name for you automatically.
This is all you have to do to add a new command! You can then bind it to a key with something like:
(global-set-key (kbd "C-c f") 'my-command)
Moreover, every key-binding is associated with an interactive function like this. You can find which function is called by which key using C-h k
and entering your key sequence. This will give you the documentation for the function that would be called on that key sequence. If you ran the code I gave you, doing C-h k C-c f
would give you a buffer containing (among other things) your doc-string:
C-c f runs the command my-command, which is an interactive Lisp
function.
It is bound to C-c f.
(my-command)
This is the docstring
So: all Emacs commands are just functions defined with (interactive)
. (Actually, there are also some primitive functions from Emacs's C core, but that isn't super important.)
This simple and elegant relationship between commands and functions--which is easy to follow in either direction--is part of what makes Emacs so easy to customize. If you ever wonder what functions your normal actions called, you can easily look them up, and if you want to add more commands, you just have one extra line in your function.
interactive
form causes it to prompt for a command name. – tripleee