I wrote the following code, but it does not work:

  (define-prefix-command 'unicode-shortcut-keymap)
  (dolist (mapping '(("- >" . "→")))
    (let ((keys (car mapping))
          (text (cdr mapping)))
      (message text)
      (define-key unicode-shortcut-keymap (kbd keys)
        (lambda () (interactive) (insert text)))))
  (global-set-key (kbd "C-c u") 'unicode-shortcut-keymap))

When I try to use it, I get the error:

Symbol’s value as variable is void: text

But text is not void, message displays the text.

How to fix this?

2 Answers 2


You don't have a closure unless your file has set lexical-binding: t as a file-local variable.

Without that, everything is using dynamic binding (in which case in your example your variable is indeed bound while your function is defined but is not still bound later on, when that function is called).

See also C-hig (elisp)Converting to Lexical Binding

  • Is it safe to enable lexical binding in the .emacs file?
    – ceving
    Nov 12, 2023 at 9:09
  • 2
    No one can tell you that. Your init file is an elisp file like any other, and the code in that file must be considered. It's not unusual to be able to make this change without needing to make other changes, but you need to read the documentation I pointed to to understand what changes might be necessary.
    – phils
    Nov 12, 2023 at 10:03

This seems to work:

(defmacro lexical (exp &rest exps)
  "Evaluate expressions with lexical scope."
  (declare (indent defun))
  `(eval '((lambda () ,exp ,@exps)) t))

  (define-prefix-command 'unicode-shortcut-keymap)
  (dolist (mapping '(("- >" . "→")))
    (let ((keys (kbd (car mapping)))
      (insert-text (lambda () (interactive) (insert (cdr mapping)))))
      (define-key unicode-shortcut-keymap keys insert-text)))
  (global-set-key (kbd "C-c u") 'unicode-shortcut-keymap))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.