Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs: Best-practice for lazy loading modes in .emacs?

Is there a best practice around lazily loading modes when encountering a relevant file extension?

At this point I have roughly 25 different Emacs modes installed, and startup has become slow. For example, although it's great to have clojure-mode at the ready, I rarely use it, and I want to avoid loading it at all unless I open a file with extension .clj. Such a "lazy require" functionality seems like the right way do mode configuration in general..

I found nothing online, so I've taken a crack at it myself.

Instead of:

(require 'clojure-mode)
(require 'tpl-mode) 

I have this:

(defun lazy-require (ext mode)
  (add-hook
   'find-file-hook
   `(lambda ()
      (when (and (stringp buffer-file-name)
                 (string-match (concat "\\." ,ext "\\'") buffer-file-name))
        (require (quote ,mode))
        (,mode)))))

(lazy-require "soy" 'soy-mode)
(lazy-require "tpl" 'tpl-mode)

This seems to work (I'm an elisp newbie so comments are welcome!), but I'm unnerved about finding nothing written about this topic online. Is this a reasonable approach?

like image 364
Rob Avatar asked Aug 04 '11 03:08

Rob


1 Answers

The facility you want is called autoloading. The clojure-mode source file, clojure-mode.el, includes a comment for how to arrange this:

;;     Add these lines to your .emacs:
;;       (autoload 'clojure-mode "clojure-mode" "A major mode for Clojure" t)
;;       (add-to-list 'auto-mode-alist '("\\.clj$" . clojure-mode))
like image 192
Sean Avatar answered Nov 16 '22 03:11

Sean