1

I'm using this code to make clickable text in a buffer:

(defun q()
  "Entry point."
  (interactive)
  (let ((buffer-name "q"))
    (get-buffer-create buffer-name)
    (switch-to-buffer buffer-name)
    (with-current-buffer buffer-name
      (q-draw "foo"))))

(defun q-draw(my-var)
  "Draw MY-VAR on click."
  (let ((map (make-sparse-keymap)))
    (define-key map [mouse-1] 'q-handle-click)
    (insert (propertize "[Click]" 'keymap map 'mouse-face 'highlight 'help-echo "Click") "  ")))

But I'd like to pass a variable to my q-handle-click function. Is this possible?

(defun q-handle-click (my-var)
  "Insert MY-VAR."
  (interactive)
  (insert (format "%s" my-var)))

I can't find an example of the proper syntax, something like this doesn't work:

(define-key map [mouse-1] '(q-handle-click my-var))

Neither does this suggestion:

(define-key map [mouse-1] `(q-handle-click ,my-var))

Is a global variable my only option?

gdonald
  • 167
  • 7
  • Does this answer your question? [How to evaluate the variables before adding them to a list?](https://emacs.stackexchange.com/questions/7481/how-to-evaluate-the-variables-before-adding-them-to-a-list) – Drew Apr 10 '22 at 16:51
  • 1
    ``(define-key map [mouse-1] `(q-handle-click ,my-var))`` – Drew Apr 10 '22 at 16:52
  • It appears my mouse click handler is no longer called when I use this code. – gdonald Apr 10 '22 at 18:23
  • Maybe I should have written this instead - just get rid of the quote: `(define-key map [mouse-1] (q-handle-click my-var))`. Presumably `q-handle-click` is a function that calculates the command to bind, taking (in this case) `my-var` as argument. Try that, to see. If that's the case then this question is instead a duplicate of another that asks about `quote`. – Drew Apr 10 '22 at 23:27

1 Answers1

1

You should bind the event to a command which calls your function with its argument.

(defun q-draw (my-var)
  "Draw MY-VAR on click."
  (let ((map (make-sparse-keymap)))
    (define-key map [mouse-1] (lambda () (interactive) (q-handle-click my-var)))
    (insert (propertize "[Click]" 'keymap map 'mouse-face 'highlight 'help-echo "Click") "  ")))

Or if you're not using lexical-binding in your library then you could use this approach:

(define-key map [mouse-1] `(lambda () (interactive) (q-handle-click ,my-var)))
phils
  • 48,657
  • 3
  • 76
  • 115