2

Is it possible to reference a local variable inside the definition of a function? Here's an example:

I have an alist text-alist consisting of keys and text snippets. I want each text snippet bound to a key in the prefix map my-text-prefix-map. The code below doesn't work, I guess because when the functions in my-text-prefix-map are run, the value of text is unknown. Is there any way to remedy this?

(mapc (lambda (text)
        (define-key my-text-prefix-map (kbd (car text))
          (lambda ()
            (interactive)
            (insert (cdr text)))))
      text-alist)
Drew
  • 77,472
  • 10
  • 114
  • 243
Erik Sjöstrand
  • 826
  • 4
  • 15

1 Answers1

7

You can use backquotes and commas to build functions dynamically:

`(lambda ()
   (interactive)
   (insert ,(cdr text)))

Or you can also enable lexical-binding to make function closures.

More information on Backquotes can be found in Emacs manual.

d12frosted
  • 384
  • 3
  • 11
zk_phi
  • 446
  • 2
  • 4
  • 3
    Whoever down-voted this, please leave a comment explaining why. Using a backquote is a very common solution to the problem. – phils May 17 '16 at 13:05
  • 3
    I didn't down vote, but I would like to see actual code for the lexbind case which, IMHO, should be the first and preferred suggestion. – YoungFrog May 26 '16 at 09:39
  • 3
    The lexbind solution uses the exact code in the question, just with a -*- lexical-binding:t -*- on the first line (a comment) of the file. – Stefan May 26 '16 at 12:14