How do I bind Emacs to set a variable?
I have a variable in Emacs called my-var that I would like to set when I press Cv. How should I do it? I've tried this:
(defun set-my-var (value)
"set my var"
(interactive)
(defvar my-var value
"a variable of mine")
)
(global-set-key "\C-v" 'set-my-var)
But it fails:
call-interactively: Wrong number of arguments: (lambda (value) "set my var"
(interactive) (defvar my-var value "a variable of mine")), 0
source to share
In fact, defvar doesn't do what you think it does: it only changes the value if there was no value before. Here's a snippet that accomplishes what you're looking for using the CTRL-u argument:
(defun set-my-var (value)
"Revised version by Charlie Martin"
(interactive "p")
(setq my-var value))
and here is an example, the code from the buffer *scratch*
(defun set-my-var (value)
"Revised version by Charlie Martin"
(interactive "p")
(setq my-var value)) ; do ^J to evaluate the defun form, showing return in the buffer.
set-my-var
(global-set-key "\C-v" 'set-my-var)
set-my-var
;Another ^J
;;; Now, what the value after ^U^V?
my-var
4
;;; Now ^U 8 ^V
my-var
8
;;; now ^U^U^V
my-var
16
source to share
It's in the argument. Take a look at the text I just posted about (interactive)
. When you bind set-my-var
to a key it looks for an argument, but since you used (interactive)
there were no arguments. What you wanted is something like (interactive "p")
to get an argument CTRL-u
or (interactive "M")
to get a string.
Read the EMACS Lisp manual on "Using Interactive".
source to share
A few other tips:
- CTRL-v is the standard bind and is quite heavily used (
scroll-up
). You'd be better off finding something that is not otherwise used. Canonically, they will be added toCTRL-c
. - It's no stranger to treating parens as if they were C staples. This is a better (more familiar) LISP style for all of us who might read your code to close all the parens at the end.
source to share