[comp.emacs] lisp function to look for a file in a list of directories ...

TRANLE@INTELLICORP.COM (Minh Tran-Le) (03/18/91)

Does anybody have a lisp function to do the lookup for a file in a 
list of directories.

I have a list of directories ("dir1" "dir2" ...) and I would like to 
find if a file xyz.u exists in one of these directories.  Something 
like the unix command `which'.

Is there a builtin function for doing it ?

Thanks,
Minh Tran-Le.
-------

hallvard@IFI.UIO.NO (Hallvard B Furuseth) (03/18/91)

> Does anybody have a lisp function to do the lookup for a file in a 
> list of directories.

(defun where-is-file (path filename &optional suffixes)
  "Search through PATH (list) for a readable FILENAME, expanded by one of the
optional SUFFIXES (string of suffixes separated by \":\"s).  Interactively,
SUFFIXES is prompted when there is a prefix arg.  Default: \".elc:.el:\"."
  (interactive
   (list (let ((path (read-minibuffer "Search path: " "load-path")))
	   (if (and (consp path) (or (stringp (car path)) (null (car path))))
	       path
	     (eval path)))
	 (read-string "Locate file: ")
	 (if current-prefix-arg
	     (read-string "Suffixes: " ".elc:.el:")
	   ".elc:.el:")))
  (let ((filelist nil) pos temp templist)
    ;; Make list of possible file names
    (setq filelist
	  (if suffixes
	      (progn
		(while (setq pos (string-match ":[^:]*$" suffixes))
		  (setq filelist (cons (concat filename
					       (substring suffixes (1+ pos)))
				       filelist))
		  (setq suffixes (substring suffixes 0 pos)))
		(cons (concat filename suffixes) filelist))
	    (list filename)))
    ;; Search PATH for a readable file in filelist
    (catch 'bar
      (if (file-name-absolute-p filename) (setq path '(nil)))
      (while path
	(setq templist filelist)
	(while (progn
		 (if (file-readable-p (setq temp (expand-file-name
						  (car templist) (car path))))
		     (progn
		       (if (interactive-p)
			   (message "%s" temp))
		       (throw 'bar temp)))
		 (setq templist (cdr templist))))
	(setq path (cdr path)))
      (if (interactive-p)
	  (message "(File %s not found)" filename))
      nil)))


			Hallvard