Emacs lisp lexical binding lambda?

I decided to write this piece of code for "git add -p":

(add-hook
 'diff-mode-hook
 (lambda()            
   (mapc (lambda(k)
           (lexical-let ((kk k))
             (define-key diff-mode-map k
               (lambda()(interactive)
                 (if (region-active-p)
                     (replace-regexp "^." kk
                                     nil
                                     (region-beginning)
                                     (region-end))
                   (insert kk)))))) (list " " "-" "+"))))

It works the way I want, it's just the ugliness of "the lexicon-let it bother me in the middle." I had to add it, because the nested lambda did not see the variable "k". Is there a better way to write this code? I would prefer some kind of magic function 'lexic-lambda, which would allow me to write:

(add-hook
 'diff-mode-hook
 (lambda()            
   (mapc (lexical-lambda(k)
                   (define-key diff-mode-map k
                     (lexical-lambda()(interactive)
                       (if (region-active-p)
                           (replace-regexp "^." k
                                           nil
                                           (region-beginning)
                                           (region-end))
                         (insert k)))))) (list " " "-" "+")))
+3
source share
1 answer
(mapc (lambda (k)
        (define-key diff-mode-map k
          `(lambda ()
             (interactive)
             (if (region-active-p)
                 (replace-regexp "^." ,k
                                 nil
                                 (region-beginning)
                                 (region-end))
               (insert ,k)))))
      (list " " "-" "+"))

Alternatively, starting with Emacs 24, you can enable local bindings locally. Just add ;; -*- lexical-binding: t -*-to the beginning of the file and your code should work without a shell lexical-let. (See C-h i g (elisp)Lexical Binding RETand C-h i g (elisp)Using Lexical Binding RET.)

+3

All Articles