Function: add-to-ordered-list

add-to-ordered-list is a byte-compiled function defined in subr.el.gz.

Signature

(add-to-ordered-list LIST-VAR ELEMENT &optional ORDER)

Documentation

Add ELEMENT to the value of LIST-VAR if it isn't there yet.

The test for presence of ELEMENT is done with eq.

The value of LIST-VAR is kept ordered based on the ORDER parameter.

If the third optional argument ORDER is a number (integer or float), set the element's list order to the given value. If ORDER is nil or omitted, do not change the numeric order of ELEMENT. If ORDER has any other value, remove the numeric order of ELEMENT if it has one.

The list order for each element is stored in LIST-VAR's list-order property. LIST-VAR cannot refer to a lexical variable.

The return value is the new value of LIST-VAR.

View in manual

Probably introduced at or before Emacs version 22.1.

Source Code

;; Defined in /usr/src/emacs/lisp/subr.el.gz
(defun add-to-ordered-list (list-var element &optional order)
  "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
The test for presence of ELEMENT is done with `eq'.

The value of LIST-VAR is kept ordered based on the ORDER
parameter.

If the third optional argument ORDER is a number (integer or
float), set the element's list order to the given value.  If
ORDER is nil or omitted, do not change the numeric order of
ELEMENT.  If ORDER has any other value, remove the numeric order
of ELEMENT if it has one.

The list order for each element is stored in LIST-VAR's
`list-order' property.
LIST-VAR cannot refer to a lexical variable.

The return value is the new value of LIST-VAR."
  (let ((ordering (get list-var 'list-order)))
    (unless ordering
      (put list-var 'list-order
           (setq ordering (make-hash-table :weakness 'key :test 'eq))))
    (when order
      (puthash element (and (numberp order) order) ordering))
    (unless (memq element (symbol-value list-var))
      (set list-var (cons element (symbol-value list-var))))
    (set list-var (sort (symbol-value list-var)
			(lambda (a b)
			  (let ((oa (gethash a ordering))
				(ob (gethash b ordering)))
			    (if (and oa ob)
				(< oa ob)
			      oa)))))))