サイトマップ 更新履歴 ニュース Elispセクション 利用手引

LoadingLispFiles

In order to load a file from EmacsLisp, use ‘load-file’. Example:

 (load-file "~/elisp/foo.el")

Do not forget the “.el” extension. Not that if a CompiledFile exists (having the “.elc” extension), then it will not be loaded. ‘load-file’ wants the exact file-name.

Usually it is better to install files in your LoadPath, though. Then, you can use either of the following:

 (load-library "sql")
 (require 'sql)

If you use ‘load-library’, then the directories in the ‘load-path’ variable will be searched, and a matching “.elc” or “.el” file will be loaded. Preference is given to the compiled version.

Using ‘require’ adds a dependency: Not only must a file with the same name (plus “.el” or “.elc” extension) exist, but in that file, Emacs wants to see a statement such as this:

 (provide 'sql)

Thus, in your package, you can ‘require’ several so-called features. This will load the files with the same name, and these files must ‘provide’ the feature. These features are recorded in the ‘features’ variable.

You can check the values of variables using ‘C-h v’.

Note that when you start using files in the LoadPath, you may end up having to deal with ConflictingLibraries.

load-directory.el can be used to load all the .el or .elc files in a directory:

 (require 'load-directory)
 (load-directory "~/.emacs.d/my-lisp")

Here’s how to do stuff only if a library successfully loads. I use this in my .emacs all the time. A typical use is: you want to load a library, and then bind some function from that library to a key. But you don’t want to attempt the binding if the library wasn’t present, because that will throw an error, or something. This is particularly handy when you use the same .emacs on different machines, not all of which have the same libraries available.

    (defmacro with-library (symbol &rest body)
      `(condition-case nil
           (progn
             (require ',symbol)
             ,@body)
    
         (error (message (format "I guess we don't have %s available." ',symbol))
                nil)))
    (put 'with-library 'lisp-indent-function 1)

(The call to put isn’t essential; it merely tells Emacs how to nicely indent the new forms.)

Here’s an example:

    (with-library tabbar 
      (tabbar-mode)
      (global-set-key [(control tab)]       'tabbar-forward)
      (global-set-key [(control shift tab)] 'tabbar-backward)
      (global-set-key [(control shift iso-lefttab)] 'tabbar-backward)
      (global-set-key [(control f10)] 'tabbar-local-mode))

In this example, if the library tabbar isn’t available, Emacs will simply put a message in the echo area to that effect, and won’t even try to call global-set-key.


A small variant on this is:

    (defmacro with-library (symbol &rest body)
      `(when (require ,symbol nil t)
         ,@body))

Usually if a package can be required then I want to see errors when body evaluates.


CategoryDotEmacs