Emacs Command Creation - A Tutorial
For example, if you don't like the letter 'e' you could bind it to a command that would display a message "Please don't use the letter 'e'". How can you do this?
If you want a more useful example of extending emacs, have a look at my emacs hooks lens.
The basics of emacs commands
The (interactive) function
(defun no-e-please ()
(message "Please don't use the letter e"))
(global-set-key (kbd "e") 'no-e-please)
However, when you try this, typing the letter 'e' results in the following error.
Wrong type argument: commandp, no-e-please
What happened here? It turns out that emacs differentiates between commands, that can be bound to a key, and normal functions which cannot. A command is simply a function that is marked interactive.
(defun no-e-please ()
(interactive)
(message "Please don't use the letter e"))
Self Insert Command
Inserting the character you pressed
(defun no-e-please ()
(interactive)
(self-insert-command 1)
(message "Please don't use the letter e"))
That is better, but it still has a couple of problems. The first thing is if we want to assign this to a key other than 'e' then it will insert the wrong character. Not wanting to ruin my configuration, I tested it with C-c C-q and it emitted ^Q.
As the parameter in self-insert-command specifies how many times the character should be inserted how do we choose the character?
Prefix commands (C-u)
(defun no-e-please (&optional n)
(interactive "p")
(let ((last-command-char ?e))
(self-insert-command (or n 1)))
(message "Please don't use the letter e"))
In Emacs you have complete control over everything
All bound keys execute emacs commands. You can define commands that behave in the same way as built-in commands, many of which are implemented in emacs-lisp.
My Other Emacs Lenses
...take a look at my other emacs lenses
-
Ediff - All About The Emacs Diff Comparison Tool
-
Ediff is a tool for comparing two different pieces of text. How is that useful? Well, consider if you sent an article for someone to proofread. When they send you the revised article (and a bill) how do you find out what they changed? Ediff is the an...
-
The Magic of Emacs Comint
-
Comint is one of the main reasons I moved to emacs after using vi/vim for 14 years. It is an emacs library for interacting with external processes. Many text editors have a way of calling out to a process and synchronously getting the result. Emacs g...
-
Emacs Hooks - An Introduction
-
Hooks provide an clean, organised mechanism for extending emacs. Any function in emacs may include one or more hooks where users can add their own functions to be run. Windows Notepad users can add .LOG to the top of a textfile in order to support a...
Curious Programmer Emacs Blog
Tips and Tutorials
Fetching RSS feed... please stand byLeave Me Feedback
If there is anything else you want to know about defining your own emacs command let me know here.






