using packages / functions only if they are available

If you use your .emacs in many places (different machines, different versions of emacs), you cannot always be sure if certain packages or functions are available. The following macros for your .emacs allow you to do things only if the package or function is available. Note: these macros are not very useful by themselves, but we will use them in later entries.
(defmacro require-maybe (feature &optional file)
  "*Try to require FEATURE, but don't signal an error if `require' fails."
  `(require ,feature ,file 'noerror)) 

(defmacro when-available (func foo)
  "*Do something if FUNCTION is available."
  `(when (fboundp ,func) ,foo)) 
If you place the macros somewhere in the beginning of your .emacs, you can use them as follows (just some examples):
;; change cursor color based on mode (insert/overwrite)
(when (require-maybe 'cursor-chg)  ; Load this library
  (change-cursor-mode 1) ; On for overwrite/read-only/input mode
  (toggle-cursor-type-when-idle 1)) ; On when idle
(when-available 'set-fringe-mode  ; emacs22+ 
  (set-fringe-mode 2))            ; don't have too much space left of col1
For more information on installing modes (and other packages), see the installing packages-entry.


Anonymous said...

Why make them macros?

Anonymous said...

Here's what I do:

(when (require 'abbrev nil t) ...)

Unknown said...

I'd have to agree; this has the smell of mere tautology.