Learning Elisp 14 - defining a minor mode
source link: https://cestlaz.github.io/post/learning-elisp-14/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Learning Elisp 14 - defining a minor mode
Another short one today. We're taking the code we already wrote and making a minor mode out of it.
In Emacs, a minor mode is a set of functionality that you can turn on
(or off) in a buffer (or globally). For example, the built in
auto-fill-mode
can be turned on in a buffer will automatically add
newlines when your line gets "too long." You can see the modes that
you currently have on using the describe-mode
function, usually
bound to C-h m
. I also currently have Hungry-Delete
mode as well
as Flyspell
and a few others. Hungry-Delete automatically deletes
multiple whitespace characters all at once so if I have five spaces
between words, I can just delete or kill once and they'll all go
away. Flyspell adds auto spell checking.
Minor modes can be turned on manually using M-x whatever-mode
command which toggles whatever mode on and off or automatically based
on hooks. For example, when you load a C file, I go into c mode which
is a major mode (more about them some other time) as well as these
minor modes:
- Auto-Save
- Corfu
- Eglot–Managed
- Eldoc
- Flymake
- Font-Lock
- Hungry-Delete
Here's specific code we go over in the video to turn on and off our new mode:
(define-minor-mode emoji-replace-mode
"fill in the docstring later"
:lighter " ER"
(if emoji-replace-mode
(add-hook 'after-change-functions #'emoji-replace-insert nil t)
(remove-hook 'after-change-functions #'emoji-replace-insert)))
The macro define-minor-mode
does all the magic. The key is that it
defines a "mode variable" - in this case named emoji-replace-mode
which tells us if we're turning the mode on or off. Based on that, we
either add or remove our hook. The :lighter " ER" sets what to show
in the mode line.
We're just scratching the surface today - just setting up the basics. Later we'll see how to clean up the variables we need for the mode - specifically our list of emojis as well as how we can select either of our emoji replacement methods - overlay a text property or replace the text. We'll also see about setting up key combos for a mode in our next elisp project.
That's it for today.
Enjoy.
Code:
The code for the series is still up here:
The videos:
Video link: https://www.youtube.com/watch?v=YBV9czwq-nw
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK