'How to toggle a command in Emacs lisp?

I would like to have a shortcut that would toggle the showing of line numbers in Emacs.

This is what I have so far:

(defun my-toggle-display-line-numbers-mode-function ()
"Toggles the line numbers"
  (interactive)
  (display-line-numbers-mode)
  )
(global-set-key [(f7)] 'my-toggle-display-line-numbers-mode-function)

But it will only turn on the line numbers. I can't turn it off, unlike when I use M-x display-line-numbers-mode which will turn on or off without any problem.

Any idea how to improve my script so it works as intended?



Solution 1:[1]

describe-function (C-h f) on display-line-numbers-mode gives the following:

Signature:
(display-line-numbers-mode &optional ARG)

Documentation:
[...]
This is a minor mode.  If called interactively, toggle the
Display-Line-Numbers mode mode. [...]

If called from Lisp, toggle the mode if ARG is toggle.  Enable
the mode if ARG is nil, omitted, or is a positive number.
Disable the mode if ARG is a negative number.

This is the automatic desciption produced by the define-minor-mode macro, and for most minor modes, the previous documentation will be exactly the same.

What we get from this:

  • When called interactively (i.e. as a command, using for example M-x display-line-numbers-mode) this acts as a toggle.
  • When called from Elisp source code, you need to specify an argument.

If you want it to act as a toggle, use (display-line-numbers-mode 'toggle) in your code. If you want something slightly more advanced than a simple toggle (for example, checking some extra conditions), use 1 and -1 as arguments to respectively enable and disable the mode (incidentally, and although the documentation is unclear, 0 counts as a negative number here, and so (display-line-numbers-mode 0) disables the mode.

As it is often the case, Emacs built-in documentation shows all there is to know. Try to get familiar with the help system, it's really good compared to a lot of softwares.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Numbra