[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

add-to-alist: new function

From: Stephen Gildea
Subject: add-to-alist: new function
Date: Mon, 12 Feb 2001 07:53:43 EST

Here's a handy function I'd like to see added to Emacs 21: add-to-alist.
It is like add-to-list, but it looks only at the cars of the element to
be added and the existing list elements when considering a match.  An
additional optional argument to add-to-alist says what to do if the car
matches but the cdr does not.

I use this function in my .emacs to update values in alists such as
default-frame-alist and auto-mode-alist; I'm sure it has other uses.
My goal in proposing this function is to allow .emacs files to be
shorter and easier to write.  The functions add-to-list and add-hook
were important steps in that direction; here is another such step.

(defun add-to-alist (alist-var elt-cons &optional no-replace)
  "Add to the value of ALIST-VAR an element ELT-CONS if it isn't there yet.
If an element with the same car as the car of ELT-CONS is already present,
replace it with ELT-CONS unless NO-REPLACE is non-nil; if a matching
element is not already present, add ELT-CONS to the front of the alist.
The test for presence of the car of ELT-CONS is done with `equal'."
  (let ((existing-element (assoc (car elt-cons) (symbol-value alist-var))))
    (if existing-element
        (or no-replace
            (rplacd existing-element (cdr elt-cons)))
      (set alist-var (cons elt-cons (symbol-value alist-var))))))

The no-replace argument is useful for setting auto-mode-alist when you
don't know whether Emacs supports a particular programming language.
For example, the following suppresses using text-mode for m4 files in
Emacs 19 but doesn't override using m4-mode in Emacs 20.

(setq default-major-mode 'text-mode)
(add-to-alist 'auto-mode-alist '("\\.m4\\'" . fundamental-mode) t)

reply via email to

[Prev in Thread] Current Thread [Next in Thread]