Search code examples
emacselisplexical-scope

lexical-binding not being enabled when evaluating .emacs


Here are some excerpts from my .emacs:

(setq lexical-binding t)
;; .emacs

(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(diff-switches "-u")
 '(tab-always-indent (quote complete)))

;...    

(require 'dired)

;...    

(dotimes (i 12) (define-key dired-mode-map (kbd (concat "<f" (number-to-string (1+ i)) ">"))
          (lambda ()
            (interactive)
            (goto-char (point-min))
            (forward-line (+ 4 i)))))

This should bind keys f1 to f12 in dired-mode to commands that jump to particular files in the list of files (ignoring . and ..). However, initially, after starting emacs, these keys don't work - I get an error message forward-line: Symbol's value as variable is void: i. However, when I go to the top line of my .emacs and press C-x C-e to evaluate that line, and then go to the last line quoted above and press C-x C-e to evaluate that dotimes expression, those function keys start working!

Why is that?

By the way, it also doesn't work if I evaluate the whole buffer.


Solution

  • It turns out that it is necessary to replace

    (setq lexical-binding t)
    

    with

    ;; -*- lexical-binding: t -*-
    

    The manual hints suggestively at this, but does not actually say so outright.