简体   繁体   中英

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 Mx 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?

describe-function ( Ch 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 ( ie as a command, using for example Mx 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM