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
  • 8

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
  • 50,977
  • 3
  • 79
  • 122