find-file.el 33.1 KB
Newer Older
Richard M. Stallman's avatar
Richard M. Stallman committed
1 2 3 4 5
;;; find-file.el --- find a file corresponding to this one given a pattern

;; Author:         Henry Guillaume <henry@qbd.com.au>
;; Keywords: c, matching, tools

Karl Heuer's avatar
Karl Heuer committed
6
;; Copyright (C) 1994, 1995 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

;;; This file is part of GNU Emacs.

;;; GNU Emacs is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 2, or (at your option)
;;; any later version.

;;; GNU Emacs is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.

;;; You should have received a copy of the GNU General Public License
;;; along with GNU Emacs; see the file COPYING.  If not, write to
;;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

;;; Commentary:

;; PURPOSE:
;; This package features a function called ff-find-other-file, which performs 
;; the following function: 
;;
;;     When in a .c file, find the first corresponding .h file in a set
;;     of directories and display it, and vice-versa from the .h file.
;;
;; Many people maintain their include file in a directory separate to their
;; src directory, and very often you may be editing a file and have a need to
;; visit the "other file". This package searches through a set of directories
;; to find that file.
;;
;; THE "OTHER FILE", or "corresponding file", generally has the same basename,
;; and just has a different extension as described by the ff-other-file-alist 
;; variable:
;;
;;   '(("\\.cc$"  (".hh" ".h"))
;;     ("\\.hh$"  (".cc" ".C" ".CC" ".cxx" ".cpp")))
;;
;; If the current file has a .cc extension, ff-find-other-file will attempt
;; to look for a .hh file, and then a .h file in some directory as described
;; below. The mechanism here is to replace the matched part of the original
;; filename with each of the corresponding extensions in turn.
;;
;; Alternatively, there are situations where the filename of the other file
;; cannot be determined easily with regexps. For example, a .c file may
;; have two corresponding .h files, for its public and private parts, or
;; the filename for the .c file contains part of the pathname of the .h
;; file, as between src/fooZap.cc and include/FOO/zap.hh. In that case, the
;; format above can be changed to include a function to be called when the
;; current file matches the regexp:
;;
;;   '(("\\.cc$"  cc-function)
;;     ("\\.hh$"  hh-function))
;;
;; These functions must return a list consisting of the possible names of the 
;; corresponding file, with or without path. There is no real need for more 
;; than one function, and one could imagine the following value for cc-other-
;; file-alist:
;;
;;    (setq cc-other-file-alist
;;        '(("\\.cc$"  ff-cc-hh-converter)
;;          ("\\.hh$"  ff-cc-hh-converter)
;;          ("\\.c$"   (".h"))
;;          ("\\.h$"   (".c" ".cc" ".C" ".CC" ".cxx" ".cpp"))))
;; 
;; ff-cc-hh-converter is included at the end of this file as a reference.
;; 
;; SEARCHING is carried out in a set of directories specified by the
;; ff-search-directories variable:
;;
;;     ("." "../../src" "../include/*" "/usr/local/*/src/*" "$PROJECT/src")
;;
;; This means that the corresponding file will be searched for first in
;; the current directory, then in ../../src, then in one of the directories
;; under ../include, and so on. The star is _not_ a general wildcard
;; character: it just indicates that the subdirectories of this directory
;; must each be searched in turn. Environment variables will be expanded in
;; the ff-search-directories variable.
;;
;; If the point is on a #include line, the file to be #included is searched
;; for in the same manner. This can be disabled with the ff-ignore-include
;; variable, or by calling ff-get-other-file instead of ff-find-other-file.
;;
;; If the file was not found, ff-find-other-file will prompt you for where
;; to create the new "corresponding file" (defaults to the current directory),
;; unless the variable ff-always-try-to-create is set to nil. 
;;
;; GIVEN AN ARGUMENT (with the ^U prefix), ff-find-other-file will get the 
;; other file in another (the other?) window (see find-file-other-window and 
;; switch-to-buffer-other-window). This can be set on a more permanent basis 
;; by setting ff-always-in-other-window to t in which case the ^U prefix will 
;; do the opposite of what was described above.
;;
;; THERE ARE FIVE AVAILABLE HOOKS, called in this order if non-nil:
;;
;; - ff-pre-find-hooks     - called before the search for the other file starts
;; - ff-not-found-hooks    - called when the other file could not be found
;; - ff-pre-load-hooks     - called just before the other file is 'loaded'
;; - ff-file-created-hooks - called when the other file is created
;; - ff-post-load-hooks    - called just after the other file is 'loaded'
;;
;; The *load-hooks allow you to place point where you want it in the other
;; file. 

;; FEEDBACK:
;; Please send me bug reports, bug fixes, and extensions, so that I can
;; merge them into the master source.

;; CREDITS:
;; Many thanks go to TUSC Computer Systems Pty Ltd for providing an environ-
;; ment that made the development of this package possible.
;;
;; Many thanks also go to all those who provided valuable feedback throughout
;; the development of this package:
;;     Rolf Ebert in particular, Fritz Knabe, Heddy Boubaker, Sebastian Kremer,
;;     Vasco Lopes Paulo, Mark A. Plaksin, Robert Lang, Trevor West, Kevin 
;;     Pereira & Benedict Lofstedt.

;; Code:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; User definable variables:

(defvar ff-pre-find-hooks nil
  "*List of functions to be called before the search for the file starts.")

(defvar ff-pre-load-hooks nil
  "*List of functions to be called before the other file is loaded.")

(defvar ff-post-load-hooks nil
  "*List of functions to be called after the other file is loaded.")

(defvar ff-not-found-hooks nil
  "*List of functions to be called if the other file could not be found.")

(defvar ff-file-created-hooks nil
  "*List of functions to be called if the other file needs to be created.")

(defvar ff-case-fold-search nil
Richard M. Stallman's avatar
Richard M. Stallman committed
145
  "*Non-nil means ignore cases in matches (see `case-fold-search').
Richard M. Stallman's avatar
Richard M. Stallman committed
146 147 148
If you have extensions in different cases, you will want this to be nil.")

(defvar ff-always-in-other-window nil
Richard M. Stallman's avatar
Richard M. Stallman committed
149 150
  "*If non-nil, find the corresponding file in another window by default.
To override this, give an argument to `ff-find-other-file'.")
Richard M. Stallman's avatar
Richard M. Stallman committed
151 152

(defvar ff-ignore-include nil
Richard M. Stallman's avatar
Richard M. Stallman committed
153
  "*If non-nil, ignore `#include' lines.")
Richard M. Stallman's avatar
Richard M. Stallman committed
154 155 156 157 158

(defvar ff-always-try-to-create t
  "*If non-nil, always attempt to create the other file if it was not found.")

(defvar ff-quiet-mode nil
Richard M. Stallman's avatar
Richard M. Stallman committed
159
  "*If non-nil, trace which directories are being searched.")
Richard M. Stallman's avatar
Richard M. Stallman committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

(defvar ff-special-constructs 
  '(
    ;; C/C++ include, for NeXTSTEP too
    ("^\#\\s *\\(include\\|import\\)\\s +[<\"]\\(.*\\)[>\"]" .
     (lambda ()
       (setq fname (buffer-substring (match-beginning 2) (match-end 2)))))

    ;; Ada import
    ("^with[ \t]+\\([a-zA-Z0-9_\\.]+\\)" .
     (lambda ()
       (setq fname (buffer-substring (match-beginning 1) (match-end 1)))
       (setq fname (concat (ada-make-filename-from-adaname fname)
                           ada-spec-suffix))))
    )
  "*A list of regular expressions specifying how to recognise special 
constructs such as include files etc, and an associated method for 
extracting the filename from that construct.")

(defvar ff-other-file-alist 'cc-other-file-alist
  "*Alist of extensions to find given the current file's extension.

This list should contain the most used extensions before the others,
since the search algorithm searches sequentially through each
Richard M. Stallman's avatar
Richard M. Stallman committed
184 185 186
directory specified in `ff-search-directories'.  If a file is not found,
a new one is created with the first matching extension (`.cc' yields `.hh').
This alist should be set by the major mode.")
Richard M. Stallman's avatar
Richard M. Stallman committed
187 188 189 190

(defvar ff-search-directories 'cc-search-directories
  "*List of directories to search for a specific file.

Richard M. Stallman's avatar
Richard M. Stallman committed
191
Set by default to `cc-search-directories', expanded at run-time.
Richard M. Stallman's avatar
Richard M. Stallman committed
192 193

This list is searched through with each extension specified in
Richard M. Stallman's avatar
Richard M. Stallman committed
194
`ff-other-file-alist' that matches this file's extension.  So the
Richard M. Stallman's avatar
Richard M. Stallman committed
195 196 197 198 199 200 201
longer the list, the longer it'll take to realise that a file
may not exist.

A typical format is 

    '(\".\" \"/usr/include/*\" \"$PROJECT/*/include\")

Richard M. Stallman's avatar
Richard M. Stallman committed
202
Environment variables can be inserted between slashes (`/').
Richard M. Stallman's avatar
Richard M. Stallman committed
203
They will be replaced by their definition. If a variable does
Richard M. Stallman's avatar
Richard M. Stallman committed
204
not exist, it is replaced (silently) with an empty string.
Richard M. Stallman's avatar
Richard M. Stallman committed
205

Richard M. Stallman's avatar
Richard M. Stallman committed
206 207 208
The stars are *not* wildcards: they are searched for together with
the preceding slash.  The star represents all the subdirectories except
`..', and each of these subdirectories will be searched in turn.")
Richard M. Stallman's avatar
Richard M. Stallman committed
209 210 211

(defvar cc-search-directories
  '("." "/usr/include/*" "/usr/local/include/*")
Richard M. Stallman's avatar
Richard M. Stallman committed
212
  "*See the description of the `ff-search-directories' variable.")
Richard M. Stallman's avatar
Richard M. Stallman committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

(defvar cc-other-file-alist
  '(
    ("\\.cc$"  (".hh" ".h"))
    ("\\.hh$"  (".cc" ".C"))

    ("\\.c$"   (".h"))
    ("\\.h$"   (".c" ".cc" ".C" ".CC" ".cxx" ".cpp"))

    ("\\.C$"   (".H"  ".hh" ".h"))
    ("\\.H$"   (".C"  ".CC"))

    ("\\.CC$"  (".HH" ".H"  ".hh" ".h"))
    ("\\.HH$"  (".CC"))

    ("\\.cxx$" (".hh" ".h"))
    ("\\.cpp$" (".hh" ".h"))
    )
  "*Alist of extensions to find given the current file's extension.

This list should contain the most used extensions before the others,
since the search algorithm searches sequentially through each directory
Richard M. Stallman's avatar
Richard M. Stallman committed
235 236
specified in `ff-search-directories'.  If a file is not found, a new one
is created with the first matching extension (`.cc' yields `.hh').")
Richard M. Stallman's avatar
Richard M. Stallman committed
237 238 239

(defvar ada-search-directories
  '("." "/usr/adainclude" "/usr/local/adainclude")
Richard M. Stallman's avatar
Richard M. Stallman committed
240
  "*See the description for the `ff-search-directories' variable.")
Richard M. Stallman's avatar
Richard M. Stallman committed
241 242 243 244 245 246 247 248 249 250

(defvar ada-other-file-alist
  '(
    ("\\.ads$" (".adb")) ;; Ada specs and bodies
    ("\\.adb$" (".ads")) ;; GNAT filename conventions
    )
  "*Alist of extensions to find given the current file's extension.

This list should contain the most used extensions before the others,
since the search algorithm searches sequentially through each directory
Richard M. Stallman's avatar
Richard M. Stallman committed
251 252
specified in `ada-search-directories'.  If a file is not found, a new one
is created with the first matching extension (`.adb' yields `.ads').
Richard M. Stallman's avatar
Richard M. Stallman committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266
")

;;;### autoload
(autoload 'ada-make-filename-from-adaname "ada-mode"
  "Determine the filename of a package/procedure from its own Ada name.")
(defvar ada-spec-suffix ".ads"  
  "*Suffix of Ada specification files.")
(make-variable-buffer-local 'ada-spec-suffix)

(defvar modula2-other-file-alist
  '(
    ("\\.mi$" (".md")) ;; Modula-2 module definition
    ("\\.md$" (".mi")) ;; and implementation.
    )
Richard M. Stallman's avatar
Richard M. Stallman committed
267
  "*See the description for the `ff-search-directories' variable.")
Richard M. Stallman's avatar
Richard M. Stallman committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; No user definable variables beyond this point!
;; ==============================================

(make-variable-buffer-local 'ff-pre-find-hooks)
(make-variable-buffer-local 'ff-pre-load-hooks)
(make-variable-buffer-local 'ff-post-load-hooks)
(make-variable-buffer-local 'ff-not-found-hooks)
(make-variable-buffer-local 'ff-file-created-hooks)
(make-variable-buffer-local 'ff-case-fold-search)
(make-variable-buffer-local 'ff-always-in-other-window)
(make-variable-buffer-local 'ff-ignore-include)
(make-variable-buffer-local 'ff-quiet-mode)
(make-variable-buffer-local 'ff-other-file-alist)
(make-variable-buffer-local 'ff-search-directories)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; User entry points

;;;###autoload
(defun ff-get-other-file (&optional in-other-window)
Richard M. Stallman's avatar
Richard M. Stallman committed
290 291
  "Find the header or source file corresponding to this file.
See also the documentation for `ff-find-other-file;.
Richard M. Stallman's avatar
Richard M. Stallman committed
292

Richard M. Stallman's avatar
Richard M. Stallman committed
293
If optional IN-OTHER-WINDOW is non-nil, find the file in another window."
Richard M. Stallman's avatar
Richard M. Stallman committed
294 295 296 297 298 299 300 301
  (interactive "P")
  (let ((ignore ff-ignore-include))
    (setq ff-ignore-include t)
    (ff-find-the-other-file in-other-window)
    (setq ff-ignore-include ignore)))

;;;###autoload
(defun ff-find-other-file (&optional in-other-window ignore-include)
Richard M. Stallman's avatar
Richard M. Stallman committed
302 303
  "Find the header or source file corresponding to this file.
Being on a `#include' line pulls in that file.
Richard M. Stallman's avatar
Richard M. Stallman committed
304

Richard M. Stallman's avatar
Richard M. Stallman committed
305 306
If optional IN-OTHER-WINDOW is non-nil, find the file in the other window.
If optional IGNORE-INCLUDE is non-nil, ignore being on `#include' lines.
Richard M. Stallman's avatar
Richard M. Stallman committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361

Variables of interest include:

 - ff-case-fold-search
   Non-nil means ignore cases in matches (see case-fold-search).
   If you have extensions in different cases, you will want this to be nil.

 - ff-always-in-other-window 
   If non-nil, always open the other file in another window, unless an
   argument is given to ff-find-other-file.

 - ff-ignore-include 
   If non-nil, ignores #include lines.

 - ff-always-try-to-create 
   If non-nil, always attempt to create the other file if it was not found.

 - ff-quiet-mode 
   If non-nil, traces which directories are being searched.

 - ff-special-constructs 
   A list of regular expressions specifying how to recognise special 
   constructs such as include files etc, and an associated method for 
   extracting the filename from that construct.

 - ff-other-file-alist
   Alist of extensions to find given the current file's extension.

 - ff-search-directories 
   List of directories searched through with each extension specified in
   ff-other-file-alist that matches this file's extension.

 - ff-pre-find-hooks 
   List of functions to be called before the search for the file starts.

 - ff-pre-load-hooks 
   List of functions to be called before the other file is loaded.

 - ff-post-load-hooks
   List of functions to be called after the other file is loaded.

 - ff-not-found-hooks
   List of functions to be called if the other file could not be found.

 - ff-file-created-hooks
   List of functions to be called if the other file has been created."
  (interactive "P")
  (let ((ignore ff-ignore-include))
    (setq ff-ignore-include ignore-include)
    (ff-find-the-other-file in-other-window)
    (setq ff-ignore-include ignore)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Support functions

Richard M. Stallman's avatar
Richard M. Stallman committed
362
(defun ff-emacs-19 ()
Richard M. Stallman's avatar
Richard M. Stallman committed
363 364 365 366 367 368 369
  (string-match "^19\\.[0-9]+\\.[0-9]+$" emacs-version))

(defun ff-xemacs ()
  (or (string-match "Lucid"  emacs-version)
      (string-match "XEmacs" emacs-version)))

(defun ff-find-the-other-file (&optional in-other-window)
Richard M. Stallman's avatar
Richard M. Stallman committed
370 371 372
  "Find the header or source file corresponding to the current file.
Being on a `#include' line pulls in that file, but see the help on
the `ff-ignore-include' variable.
Richard M. Stallman's avatar
Richard M. Stallman committed
373

Richard M. Stallman's avatar
Richard M. Stallman committed
374
If optional IN-OTHER-WINDOW is non-nil, find the file in another window."
Richard M. Stallman's avatar
Richard M. Stallman committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651

  (let (match           ;; matching regexp for this file
        suffixes        ;; set of replacing regexps for the matching regexp
        action          ;; function to generate the names of the other files
        fname           ;; basename of this file
        pos             ;; where we start matching filenames
        stub            ;; name of the file without extension
        alist           ;; working copy of the list of file extensions
        pathname        ;; the pathname of the file or the #include line
        default-name    ;; file we should create if none found
        format          ;; what we have to match    
        found           ;; name of the file or buffer found - nil if none 
        dirs            ;; local value of ff-search-directories
        no-match)       ;; whether we know about this kind of file

    (if ff-pre-find-hooks
        (run-hooks 'ff-pre-find-hooks))

    (message "Working...")

    (setq dirs
          (if (symbolp ff-search-directories)
              (ff-list-replace-env-vars (symbol-value ff-search-directories))
            (ff-list-replace-env-vars ff-search-directories)))

    (save-excursion
      (beginning-of-line 1)
      (setq fname (ff-treat-as-special)))

    (cond
     ((and (not ff-ignore-include) fname)
      (setq default-name fname)
      (setq found (ff-get-file dirs fname nil in-other-window)))

     ;; let's just get the corresponding file
     (t
      (setq alist (if (symbolp ff-other-file-alist)
                      (symbol-value ff-other-file-alist)
                    ff-other-file-alist)
            pathname (if (buffer-file-name)
                         (buffer-file-name)
                       "/none.none"))

      (string-match ".*/\\(.+\\)$" pathname)
      (setq fname (substring pathname (match-beginning 1) (match-end 1))
            no-match nil
            match (car alist))

      ;; find the table entry corresponding to this file
      (setq pos (ff-string-match (car match) fname))
      (while (and match (if (and pos (>= pos 0)) nil (not pos)))
        (setq alist (cdr alist))
        (setq match (car alist))
        (setq pos (ff-string-match (car match) fname)))

      ;; no point going on if we haven't found anything
      (if (not match)
          (setq no-match t)

        ;; otherwise, suffixes contains what we need
        (setq suffixes (car (cdr match))
              action (car (cdr match))
              found nil)

        ;; if we have a function to generate new names, 
        ;; invoke it with the name of the current file
        (if (and (atom action) (fboundp action))
            (progn
              (setq suffixes (funcall action (buffer-file-name))
                    match (cons (car match) (list suffixes))
                    stub nil
                    default-name (car suffixes)))

          ;; otherwise build our filename stub
          (cond 

           ;; get around the problem that 0 and nil both mean false!
           ((= pos 0)
            (setq format "")
            (setq stub "")
            )

           (t
            (setq format (concat "\\(.+\\)" (car match)))
            (string-match format fname)
            (setq stub (substring fname (match-beginning 1) (match-end 1)))
            ))

          ;; if we find nothing, we should try to get a file like this one
          (setq default-name
                (concat stub (car (car (cdr match))))))

        ;; do the real work - find the file
        (setq found 
              (ff-get-file dirs
                           stub
                           suffixes 
                           in-other-window)))))

    (cond
     (no-match                     ;; could not even determine the other file
      (message ""))

     (t 
      (cond

       ((not found)                ;; could not find the other file

        (if ff-not-found-hooks     ;; run the hooks
            (run-hooks 'ff-not-found-hooks))

        (cond 
         (ff-always-try-to-create  ;; try to create the file
          (let (name pathname)

            (setq name
                  (expand-file-name
                   (read-file-name
                    (format "Find or create %s in: " default-name)
                    default-directory default-name nil)))
            
            (setq pathname
                  (if (file-directory-p name)
                      (concat (file-name-as-directory name) default-name)
                    (setq found name)))
            
            (ff-find-file pathname in-other-window t)))

         (t                        ;; don't create the file, just whinge
          (message "no file found for %s" fname))))

       (t                          ;; matching file found
        nil))))

    found))                        ;; return buffer-name or filename

(defun ff-get-file (search-dirs fname-stub &optional suffix-list other-window)
  "Find a file in the SEARCH-DIRS with the given FILENAME (or filename stub). 
If (optional) SUFFIXES is nil, search for fname, otherwise search for fname 
with each of the given suffixes. Gets the file or the buffer corresponding 
to the name of the first file found, or nil.

Arguments: (search-dirs fname-stub &optional suffix-list in-other-window)
"
  (let ((filename (ff-get-file-name search-dirs fname-stub suffix-list)))
            
    (cond 
     ((not filename)
      nil)

     ((bufferp (get-buffer filename))
      (ff-switch-to-buffer filename other-window)
      filename)
               
     ((file-exists-p filename)
      (ff-find-file filename other-window nil)
      filename)

     (t
      nil))))

(defun ff-get-file-name (search-dirs fname-stub &optional suffix-list)
  "Find a file in the SEARCH-DIRS with the given FILENAME (or filename stub). 
If (optional) SUFFIXES is nil, search for fname, otherwise search for fname 
with each of the given suffixes. Returns the name of the first file found.

Arguments: (search-dirs fname-stub &optional suffix-list)
"
  (let* (dirs         ;; working copy of dirs to search
         dir          ;; the current dir considered
         file         ;; filename being looked for
         rest         ;; pathname after first /*
         this-suffix  ;; the suffix we are currently considering
         suffixes     ;; working copy of suffix-list
         filename     ;; built filename
         blist        ;; list of live buffers
         buf          ;; current buffer in blist
         found)       ;; whether we have found anything

    (setq suffixes suffix-list)

    ;; suffixes is nil => fname-stub is the file we are looking for
    ;; otherwise fname-stub is a stub, and we append a suffix
    (if suffixes
        (setq this-suffix (car suffixes))
      (setq this-suffix "")
      (setq suffixes (list "")))
            
    ;; find whether the file is in a buffer first
    (while (and suffixes (not found))
      (setq filename (concat fname-stub this-suffix))

      (if (not ff-quiet-mode)
          (message "finding buffer %s..." filename))

      (if (bufferp (get-buffer filename))
          (setq found filename))

      (setq blist (buffer-list))
      (setq buf (buffer-name (car blist)))
      (while (and blist (not found))

        (if (string-match (concat filename "<[0-9]+>") buf)
            (setq found buf))

        (setq blist (cdr blist))
        (setq buf (buffer-name (car blist))))

      (setq suffixes (cdr suffixes))
      (setq this-suffix (car suffixes)))

    ;; now look for the real file
    (setq dirs search-dirs)
    (setq dir  (car dirs))
    (while (and (not found) dirs)

      (setq suffixes suffix-list)

      ;; if dir does not contain '/*', look for the file
      (if (and dir (not (string-match "\\([^*]*\\)/\\\*\\(/.*\\)*" dir)))
          (progn 
            
            ;; suffixes is nil => fname-stub is the file we are looking for
            ;; otherwise fname-stub is a stub, and we append a suffix
            (if suffixes
                (setq this-suffix (car suffixes))
              (setq this-suffix "")
              (setq suffixes (list "")))
            
            (while (and suffixes (not found))

              (setq filename (concat fname-stub this-suffix))
              (setq file (concat dir "/" filename))
              
              (if (not ff-quiet-mode)
                  (message "finding %s..." file))

              (if (file-exists-p file)
                  (setq found file))
              
              (setq suffixes (cdr suffixes))
              (setq this-suffix (car suffixes))))

        ;; otherwise dir matches the '/*', so search each dir separately
        (progn
          (if (match-beginning 2)
              (setq rest (substring dir (match-beginning 2) (match-end 2)))
            (setq rest "")
            )
          (setq dir  (substring dir (match-beginning 1) (match-end 1)))

          (let ((dirlist (ff-all-dirs-under dir '("..")))
                this-dir compl-dirs)

            (setq this-dir (car dirlist))
            (while dirlist
              (setq compl-dirs
                    (append
                     compl-dirs
                     (list (concat this-dir rest))
                     ))
              (setq dirlist  (cdr dirlist))
              (setq this-dir (car dirlist)))

            (if compl-dirs
                (setq found (ff-get-file-name compl-dirs
                                              fname-stub
                                              suffix-list))))))
      (setq dirs (cdr dirs))
      (setq dir (car dirs)))

    (if found
        (message "%s found" found))

    found))

(defun ff-string-match (regexp string &optional start)
Richard M. Stallman's avatar
Richard M. Stallman committed
652 653 654
  "Like string-match (which see), but set `case-fold-search' temporarily.
The value used comes from `ff-case-fold-search'."
  (let ((case-fold-search ff-case-fold-search))
Richard M. Stallman's avatar
Richard M. Stallman committed
655
    (if regexp
Richard M. Stallman's avatar
Richard M. Stallman committed
656
	(string-match regexp string start))))
Richard M. Stallman's avatar
Richard M. Stallman committed
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674

(defun ff-list-replace-env-vars (search-list)
  "Replace environment variables (of the form $VARIABLE) in SEARCH-LIST."
  (let (list
        (var (car search-list)))
    (while search-list
      (if (string-match "\\(.*\\)\\$[({]*\\([a-zA-Z0-9_]+\\)[)}]*\\(.*\\)" var)
          (setq var
                (concat
                 (substring var (match-beginning 1) (match-end 1))
                 (getenv (substring var (match-beginning 2) (match-end 2)))
                 (substring var (match-beginning 3) (match-end 3)))))
      (setq search-list (cdr search-list))
      (setq list (cons var list))
      (setq var (car search-list)))
    (setq search-list (reverse list))))

(defun ff-treat-as-special ()
Richard M. Stallman's avatar
Richard M. Stallman committed
675 676
  "Returns the file to look for if the construct was special, else nil.
The construct is defined in the variable `ff-special-constructs' (which see)."
Richard M. Stallman's avatar
Richard M. Stallman committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
  (let* (fname
         (list ff-special-constructs)
         (elem (car list))
         (regexp (car elem))
         (match (cdr elem)))
    (while (and list (not fname))
      (if (and (looking-at regexp) match)
          (setq fname (funcall match)))
      (setq list (cdr list))
      (setq elem (car list))
      (setq regexp (car elem))
      (setq match (cdr elem)))
    fname))

(defun ff-basename (string)
Richard M. Stallman's avatar
Richard M. Stallman committed
692
  "Return the basename of PATHNAME."
Richard M. Stallman's avatar
Richard M. Stallman committed
693 694 695 696 697
  (setq string (concat "/" string))
  (string-match ".*/\\([^/]+\\)$" string)
  (setq string (substring string (match-beginning 1) (match-end 1))))

(defun ff-all-dirs-under (here &optional exclude)
Richard M. Stallman's avatar
Richard M. Stallman committed
698
  "Get all the directory files under directory HERE.
Richard M. Stallman's avatar
Richard M. Stallman committed
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
Exclude all files in the optional EXCLUDE list."
  (if (file-directory-p here)
      (condition-case nil
          (progn
            (let ((files (directory-files here t))
                  (dirlist (list))
                  file)
              (while files
                (setq file (car files))
                (if (and
                     (file-directory-p file)
                     (not (member (ff-basename file) exclude)))
                    (setq dirlist (cons file dirlist)))
                (setq files (cdr files)))
              (setq dirlist (reverse dirlist))))
        (error nil))
    nil))

(defun ff-switch-file (f1 f2 file &optional in-other-window new-file)
Richard M. Stallman's avatar
Richard M. Stallman committed
718 719
  "Call F1 or F2 on FILE, according to IN-OTHER-WINDOW.
In addition, this runs various hooks.
Richard M. Stallman's avatar
Richard M. Stallman committed
720

Richard M. Stallman's avatar
Richard M. Stallman committed
721 722 723
Either F1 or F2 receives FILE as the sole argument.
The decision of which one to call is based on IN-OTHER-WINDOW
and on the global variable `ff-always-in-other-window'.
Richard M. Stallman's avatar
Richard M. Stallman committed
724

Richard M. Stallman's avatar
Richard M. Stallman committed
725 726 727 728 729
F1 and F2 are typically `find-file' / `find-file-other-window'
or `switch-to-buffer' / `switch-to-buffer-other-window' function pairs.

If optional NEW-FILE is t, then a special hook (`ff-file-created-hooks') is 
called before `ff-post-load-hooks'."
Richard M. Stallman's avatar
Richard M. Stallman committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743
  (if ff-pre-load-hooks
      (run-hooks 'ff-pre-load-hooks))
  (if (or
       (and in-other-window (not ff-always-in-other-window))
       (and (not in-other-window) ff-always-in-other-window))
      (funcall f2 file)
    (funcall f1 file))
  (if new-file
      (if ff-file-created-hooks
          (run-hooks 'ff-file-created-hooks)))
  (if ff-post-load-hooks
      (run-hooks 'ff-post-load-hooks)))

(defun ff-find-file (file &optional in-other-window new-file)
Richard M. Stallman's avatar
Richard M. Stallman committed
744
  "Like `find-file' (which see), but may put the file in another window."
Richard M. Stallman's avatar
Richard M. Stallman committed
745 746 747 748 749
  (ff-switch-file 'find-file 
                  'find-file-other-window 
                  file in-other-window new-file))

(defun ff-switch-to-buffer (file &optional in-other-window)
Richard M. Stallman's avatar
Richard M. Stallman committed
750
  "Like `switch-to-buffer' (which see), but may put the buffer in another window."
Richard M. Stallman's avatar
Richard M. Stallman committed
751 752 753 754 755 756

  (ff-switch-file 'switch-to-buffer 
                  'switch-to-buffer-other-window 
                  file in-other-window nil))

(cond 
Richard M. Stallman's avatar
Richard M. Stallman committed
757
 ((ff-emacs-19)
Richard M. Stallman's avatar
Richard M. Stallman committed
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
  (defun ff-goto-click (event)
    (set-buffer (window-buffer (posn-window (event-end event))))
    (goto-char (posn-point (event-end event))))

  ;;;###autoload
  (defun ff-mouse-find-other-file (event)
    "Visit the file you click on."
    (interactive "e")
    (save-excursion
      (ff-goto-click event)
      (ff-find-other-file nil)))

  ;;;###autoload
  (defun ff-mouse-find-other-file-other-window (event)
    "Visit the file you click on."
    (interactive "e")
    (save-excursion
      (ff-goto-click event)
      (ff-find-other-file t)))

  ;;;###autoload
  (defun locate-file (fname dirs &optional suffix-list ignore-perms)
    "Defines XEmacs look-alike locate-file for GNU Emacs-19."
    (interactive)
    (ff-get-file dirs fname suffix-list)) 
  )

 ((ff-xemacs)

  ;;;###autoload
  (defun ff-mouse-find-other-file (event)
    "Visit the file you click on."
    (interactive "@e")
    (save-excursion
      (mouse-set-point event)
      (ff-find-other-file nil)))

  ;;;###autoload
  (defun ff-mouse-find-other-file-other-window (event)
    "Visit the file you click on."
    (interactive "@e")
    (save-excursion
      (mouse-set-point event)
      (ff-find-other-file t))) 
  ))

(provide 'find-file)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This section offers an example of user defined function to select files

Richard M. Stallman's avatar
Richard M. Stallman committed
809 810 811
(defun ff-upcase-p (string &optional start end)
  "Return t if this string is all uppercase.
Given START and/or END, checks between these characters."
Richard M. Stallman's avatar
Richard M. Stallman committed
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
  (let (match str)
    (if (not start)
        (setq start 0))
    (if (not end)
        (setq end (length string)))
    (if (= start end)
        (setq end (1+ end)))
    (setq str (substring string start end))
    (if (and 
         (ff-string-match "[A-Z]+" str)
         (setq match (match-data))
         (= (car match) 0)
         (= (car (cdr match)) (length str)))
        t
      nil)))

(defun ff-cc-hh-converter (arg)
Richard M. Stallman's avatar
Richard M. Stallman committed
829 830 831
  "Discriminate file extensions.
Build up a new file list based possibly on part of the directory name
and the name of the file passed in."
Richard M. Stallman's avatar
Richard M. Stallman committed
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
  (ff-string-match "\\(.*\\)/\\([^/]+\\)/\\([^.]+\\).\\([^/]+\\)$" arg)
  (let ((path (if (match-beginning 1) 
                  (substring arg (match-beginning 1) (match-end 1)) nil))
        (dire (if (match-beginning 2) 
                  (substring arg (match-beginning 2) (match-end 2)) nil))
        (file (if (match-beginning 3) 
                  (substring arg (match-beginning 3) (match-end 3)) nil))
        (extn (if (match-beginning 4) 
                  (substring arg (match-beginning 4) (match-end 4)) nil))
        return-list)
    (cond
     ;; fooZapJunk.cc => ZapJunk.{hh,h} or fooZapJunk.{hh,h}
     ((and (string= extn "cc") 
           (ff-string-match "^\\([a-z]+\\)\\([A-Z].+\\)$" file))
      (let ((stub  (substring file (match-beginning 2) (match-end 2))))
        (setq dire (upcase (substring file (match-beginning 1) (match-end 1))))
        (setq return-list (list (concat stub ".hh")
                                (concat stub ".h")
                                (concat file ".hh")
                                (concat file ".h")))
        ))
     ;; FOO/ZapJunk.hh => fooZapJunk.{cc,C} or ZapJunk.{cc,C}
Richard M. Stallman's avatar
Richard M. Stallman committed
854
     ((and (string= extn "hh") (ff-upcase-p dire) file)
Richard M. Stallman's avatar
Richard M. Stallman committed
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
      (let ((stub (concat (downcase dire) file)))
        (setq return-list (list (concat stub ".cc")           
                                (concat stub ".C")
                                (concat file ".cc")
                                (concat file ".C")))
        ))
     ;; zap.cc => zap.hh or zap.h
     ((string= extn "cc")
      (let ((stub file))
        (setq return-list (list (concat stub ".hh")
                                (concat stub ".h")))
        ))
     ;; zap.hh => zap.cc or zap.C
     ((string= extn "hh")
      (let ((stub file))
        (setq return-list (list (concat stub ".cc")
                                (concat stub ".C")))
        ))
     (t 
      nil))
    
    return-list))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This section offers an example of user defined function to place point.
;; The regexps are Ada specific.

(defvar ff-function-name nil "Name of the function we are in.")

(defvar ada-procedure-start-regexp)
(defvar ada-package-start-regexp)

;; bind with (setq ff-pre-load-hooks 'ff-which-function-are-we-in)
;;
(defun ff-which-function-are-we-in ()
Richard M. Stallman's avatar
Richard M. Stallman committed
890 891
  "Return the name of the function whose definition/declaration point is in.
Also remember that name in `ff-function-name'."
Richard M. Stallman's avatar
Richard M. Stallman committed
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907

  (setq ff-function-name nil)

  (save-excursion
    (if (re-search-backward ada-procedure-start-regexp nil t)
        (setq ff-function-name (buffer-substring (match-beginning 0)
                                                 (match-end 0)))
      ; we didn't find a procedure start, perhaps there is a package
      (if (re-search-backward ada-package-start-regexp nil t)
          (setq ff-function-name (buffer-substring (match-beginning 0)
                                                   (match-end 0)))
        ))))

;; bind with (setq ff-post-load-hooks 'ff-set-point-accordingly)
;;
(defun ff-set-point-accordingly ()
Richard M. Stallman's avatar
Richard M. Stallman committed
908
  "Find the function specified in `ff-function-name'.
909
That name was previously determined by `ff-which-function-are-we-in'."
Richard M. Stallman's avatar
Richard M. Stallman committed
910 911 912 913 914 915 916
  (if ff-function-name
      (progn
        (goto-char (point-min))
        (search-forward ff-function-name nil t))))

;; find-file.el ends here