How to toggle minor modes in Emacs 24

There is a little underdocumented change in Emacs 24 about minor modes toggling. (To be fair, it still isn’t the official release.)

One of the beauty of Emacs is how easy it is to bind it to your will. Say I want to have flyspell-mode and auto-fill-mode activated when I write for this blog. I could M-x each of them… or I can bind <f7> to a lambda function, composed of a call to every mode I need. Here is a little example I use for my daily work:

(global-set-key (kbd "<f7>") ; F7 - Activate auto-fill-mode, flyspell-mode and abbrev-mode
                '(lambda()(interactive)
                   (auto-fill-mode)
                   (flyspell-mode)
                   (abbrev-mode)
                   (message "Toggle Fill Flyspell Abbrev")))

Bam! 3 minor modes activated instantly! Unfortunately, this doesn’t work for Emacs 24. The reason is a little change in how the modes can be activated. In all previous version, this was the normal behavior:

  • Argument NIL -> toggle
  • Argument 1 -> On
  • Argument -1 -> Off

For example, (auto-fill-mode 1) would have activated the mode no matter what.

The new behavior is quite different and might break some of your code, so you should check into it. Here is what changed:

  • (When called from Lisp) Argument nil -> On

See what they did there? Now you can’t toggle in a program like you would if called interactively (which is to say, with M-x).

Solution?

Here is what I got after asking to the Emacs developers’ mailing list:

  1. (foo-mode (if foo-mode -1 1))
  2. (foo-mode ‘toggle)

I would be careful with the solution #1, because the variable foo-mode might not have the same name as the function foo-mode.

My recommendation is to use #2.

Now my code looks like this:

(global-set-key (kbd "<f7>") ; F7 - Activate auto-fill-mode, flyspell-mode and abbrev-mode
                '(lambda()(interactive)
                   (auto-fill-mode 'toggle)
                   (flyspell-mode 'toggle)
                   (abbrev-mode 'toggle)
                   (message "Toggle Fill Flyspell Abbrev")))

One response to “How to toggle minor modes in Emacs 24

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: