Emacs: Best-practice for lazy loading modes in .em

2019-02-04 20:05发布

问题:

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?

回答1:

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))


回答2:

This is one way,

(provide 'my-slime)
(eval-after-load "slime"
  '(progn
     (setq slime-lisp-implementations
           '((sbcl ("/usr/bin/sbcl"))
             (clisp ("/usr/bin/clisp")))
           common-lisp-hyperspec-root "/home/sujoy/documents/hyperspec/")
     (slime-setup '(slime-asdf
                    slime-autodoc
                    slime-editing-commands
                    slime-fancy-inspector
                    slime-fontifying-fu
                    slime-fuzzy
                    slime-indentation
                    slime-mdot-fu
                    slime-package-fu
                    slime-references
                    slime-repl
                    slime-sbcl-exts
                    slime-scratch
                    slime-xref-browser))
     (slime-autodoc-mode)
     (setq slime-complete-symbol*-fancy t)
     (setq slime-complete-symbol-function 'slime-fuzzy-complete-symbol)
(add-hook 'lisp-mode-hook (lambda () (slime-mode t)))))

(require 'slime)

along with,

;; slime mode
(autoload 'slime "my-slime" "Slime mode." t)
(autoload 'slime-connect "my-slime" "Slime mode." t)