(defvar include-path '("/usr/include/" 
		       "/usr/include/sys/" 
		       "/usr/include/X11/"
		       "/usr/athena/include/"
		       "./")
  "*List of pathnames searched by find-include-file")

(defvar include-do-whole-path nil
  "*Search whole include path, or just to first hit?")


(defun find-include-file ()
  "Searches for a [C header] file in the pathlist specified
in include-path.  If the point is on a line in the form
#include <filename.h> or #include \"filename.h\", the line
is parsed and the appropriate filename is sarched for.  If
it is present in more than one place in the include path, 
the user will be notified."
  (interactive)
  (beginning-of-line)
  (if (not (looking-at (regexp-quote "#include")))
      (find-include-file-in-pathlist 
	(read-file-name "Find include file: " ""))
    (let ((p (match-end 0))
	  (e (progn (end-of-line) (point)))
	  start ch)
      (goto-char p)
      (if (re-search-forward "\"\\|<" e)
	  (progn
	    (setq start (match-end 0))
	    (goto-char start)
	    (or (re-search-forward "\"\\|>" e)
		(error "Matching brace not found"))
	    (find-include-file-in-pathlist 
	      (buffer-substring start (1- (match-end 0)))))))))

(defun find-include-file-in-pathlist (fname)
  "Search for the named file in include-path and bring it
into a buffer.  If the file is present in more than one
directory in the path, notify the user."
  (if (eq ?/ (aref fname 0))		;absolute pathname?
      (find-file fname)
    (let ((paths include-path)
      found-list)
      (while paths
	(if (file-exists-p 
	      (concat (car paths) fname))
	    (progn
	      (setq found-list (cons (car paths) found-list))
	      (or include-do-whole-path (setq paths nil))))
	(setq paths (cdr paths)))
      (if found-list
	  (progn
	    (find-file (concat (car found-list) fname))
	    (if (cdr found-list)
		(message (format "%s is in: %s"
				 fname found-list))
	      (message (format "Found include file %s in %s"
			       fname (car found-list)))))
	(error (format "Include file %s not found" fname))))))
