6

I have something like below (from the answer) in my init file:

(add-hook 'LaTeX-mode-hook 'my-latex-hook)

(defun my-latex-hook ()
  (require 'tex-site)
  (define-key LaTeX-mode-map "-" (lambda () (interactive) (insert "_")))
  (define-key LaTeX-mode-map "_" (lambda () (interactive) (insert "-")))
  (define-key LaTeX-mode-map "6" (lambda () (interactive) (insert "^")))
  (define-key LaTeX-mode-map "^" (lambda () (interactive) (insert "6"))))

When I byte-compile the init file, there is a message: Warning: reference to free variable LaTeX-mode-map. The function works without problem in LaTeX-mode. Should one take this message serious? Is there a better way to write the above function in order to prevent this warning?

Name
  • 7,689
  • 4
  • 38
  • 84

2 Answers2

4

If you're going for a single file init, you can add this declare:

(defvar LaTeX-mode-map)

If you have multiple files, like I do, just require tex-site at top level, see ora-latex.el. What I do is load this always:

(add-hook 'LaTeX-mode-hook 'my-latex-hook)

But then my-latex-hook is an autoloaded function in ora-latex.el. So the whole file isn't loaded until necessary. The my-latex-hook function is usually empty, unless I need to enable some minor modes or set mode-local vars. The define-key statements are run only once instead of each time a new tex file is opened, which isn't a big deal but it's nice to have.

abo-abo
  • 13,943
  • 1
  • 29
  • 43
3

What you are doing is safe, because when your hook is executed LaTeX is already loaded and LaTeX-mode-map is defined. Byte compiler cannot know that because when it compiles your file LaTeX mode is not loaded and thus symbol LaTeX-mode-map considered free variable.

Apart from the technique you use, you can use eval-after-load:

(eval-after-load 'my-file
  ;; use functions from ‘my-file’ without fear
  )

If you don't want to see the warning you can load file that contains LaTeX-mode-map only when you byte-compile your file:

(eval-when-compile
  (require 'my-file))

This will not slow down Emacs on startup since my-file will be loaded only when your file is going to be compiled.

Many people will argue that you shouldn't compile your configuration files, though.

Mark Karpov
  • 4,893
  • 1
  • 24
  • 53