Search code examples
emacselisp

Emacs Lisp: how to avoid inserting a duplicate list item?


How do I check if a string is already in a list in Emacs Lisp? I need to check if a certain path string is already in exec-path, and then add it to that list if it's not.


Solution

  • The function add-to-list will check automatically before adding

    (setq a '(1 2 3))
    (add-to-list 'a 4)
    (add-to-list 'a 3)
    

    will result in a equal to (4 1 2 3)

    From Emacs 26 C-h f add-to-list:

    (add-to-list LIST-VAR ELEMENT &optional APPEND COMPARE-FN)
    
    Add ELEMENT to the value of LIST-VAR if it isn’t there yet.
    The test for presence of ELEMENT is done with ‘equal’, or with
    COMPARE-FN if that’s non-nil.
    If ELEMENT is added, it is added at the beginning of the list,
    unless the optional argument APPEND is non-nil, in which case
    ELEMENT is added at the end.
    
    The return value is the new value of LIST-VAR.
    
    This is handy to add some elements to configuration variables,
    but please do not abuse it in Elisp code, where you are usually
    better off using ‘push’ or ‘cl-pushnew’.
    
    If you want to use ‘add-to-list’ on a variable that is not
    defined until a certain package is loaded, you should put the
    call to ‘add-to-list’ into a hook function that will be run only
    after loading the package.  ‘eval-after-load’ provides one way to
    do this.  In some cases other hooks, such as major mode hooks,
    can do the job.