Here's a quick answer --
(defun my-toggle-var (var)
(let* ((def (variable-at-point))
(def (and def
(not (numberp def))
(memq (symbol-value def) '(nil t))
"Toggle value of variable: "
obarray (lambda (c)
(unless (symbolp c) (setq c (intern c)))
(and (boundp c) (memq (symbol-value c) '(nil t))))
'must-confirm nil 'variable-name-history def))))
(let ((sym (intern var)))
(set sym (not (symbol-value sym)))
(message "`%s' is now `%s'" var (symbol-value sym))))
But if you use Icicles then you can just use command
icicle-toggle-option (with a negative prefix arg, if you want any variable, and not just a user option):
icicle-toggle-option is an interactive compiled Lisp function in
It is bound to menu-bar options icicles icicle-toggle-option.
Toggle option’s value. This makes sense for binary (toggle) options.
By default, completion candidates are limited to user options that
have ‘boolean’ custom types. However, there are many "binary" options
that allow other non-nil values than t.
You can use a prefix argument to change the set of completion
candidates, as follows:
- With a non-negative prefix arg, all user options are candidates.
- With a negative prefix arg, all variables are candidates.
Read input, then act on it.
Input-candidate completion and cycling are available. While cycling,
these keys with prefix ‘C-’ are active:
‘C-mouse-2’, ‘C-return’ - Act on current completion candidate only
‘C-down’, ‘C-wheel-down’ - Move to next completion candidate and act
‘C-up’, ‘C-wheel-up’ - Move to previous completion candidate and act
‘C-next’ - Move to next apropos-completion candidate and act
‘C-prior’ - Move to previous apropos-completion candidate and act
‘C-end’ - Move to next prefix-completion candidate and act
‘C-home’ - Move to previous prefix-completion candidate and act
‘C-!’ - Act on *all* candidates, successively (careful!)
When candidate action and cycling are combined (e.g. ‘C-next’), user
option ‘icicle-act-before-cycle-flag’ determines which occurs first.
With prefix ‘C-M-’ instead of ‘C-’, the same keys (‘C-M-mouse-2’,
‘C-M-RET’, ‘C-M-down’, and so on) provide help about candidates.
Use ‘mouse-2’, ‘RET’, or ‘S-RET’ to finally choose a candidate, or
‘C-g’ to quit.
This is an Icicles command - see command ‘icicle-mode’.