tags:

views:

168

answers:

3

I've got a variable in Emacs called my-var that I'd like to set whenever I press C-v. How do I do that? I 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 that fails:

call-interactively: Wrong number of arguments: (lambda (value) "set my var"
(interactive) (defvar my-var value "a variable of mine")), 0
+3  A: 

It's in the argument. Look over at the text I just posted about (interactive). When you bind set-my-var to a key, it's looking for an argument, but since you used (interactive) there's no argument to be had. What you wanted is something like (interactive "p") to get the CTRL-u argument, or (interactive "M") to get a string.

Read the EMACS Lisp manual on "Using Interactive."

Charlie Martin
Thanks, that allows me to set the variable once. But after it's set once, i can't use C-v to change it anymore.
mike
See the code below. You're using defvar mistakenly.
Charlie Martin
+2  A: 

A couple of other hints:

  • CTRL-v is a standard binding and pretty heavily used (scroll-up). You'd be better off finding something that's not otherwise used. Canonically, those would be added to the CTRL-c keymap.
  • Don't get in the habit of treating parens as if they were C braces. It's better (more customary) LISP style for the rest of us who might read your code to just close all the parens at the end.
Charlie Martin
The code's just an example; the real-life problem is more complex and is bound to C-X P
mike
+4  A: 

Actually, defvar doesn't do what you think it does either: it only changes the value IF there was no value before. Here's a chunk that does 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's an example, code from the *scratch* buffer

(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's the value after ^U^V?
my-var
4
;;; Now ^U 8 ^V
my-var
8
;;; now ^U^U^V
my-var
16
Charlie Martin