]> code.delx.au - gnu-emacs/blob - lisp/ffap.el
(ediff-context-diff-label-regexp): Recognize -u format better.
[gnu-emacs] / lisp / ffap.el
1 ;;; ffap.el --- find file or url at point
2
3 ;; Copyright (C) 1995, 1996 Free Software Foundation, Inc.
4
5 ;; Author: Michelangelo Grigni <mic@mathcs.emory.edu>
6 ;; Created: 29 Mar 1993
7 ;; Keywords: files, hypermedia, matching, mouse
8 ;; X-Latest: ftp://ftp.mathcs.emory.edu:/pub/mic/emacs/
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 \f
28 ;;; Commentary:
29 ;;
30 ;; Command find-file-at-point replaces find-file. With a prefix, it
31 ;; behaves exactly like find-file. Without a prefix, it first tries
32 ;; to guess a default file or url from the text around the point
33 ;; (`ffap-require-prefix' swaps these behaviors). This is useful for
34 ;; following references in situations such as mail or news buffers,
35 ;; README's, MANIFEST's, and so on. Submit bugs or suggestions with
36 ;; M-x ffap-bug.
37 ;;
38 ;; For the default installation, byte-compile ffap.el somewhere in
39 ;; your `load-path' and add these two lines to your .emacs file:
40 ;;
41 ;; (require 'ffap) ; load the package
42 ;; (ffap-bindings) ; do default key bindings
43 ;;
44 ;; ffap-bindings makes the following global key bindings:
45 ;;
46 ;; C-x C-f find-file-at-point (abbreviated as ffap)
47 ;; C-x 4 f ffap-other-window
48 ;; C-x 5 f ffap-other-frame
49 ;; S-mouse-3 ffap-at-mouse
50 ;;
51 ;; ffap-bindings also adds hooks to make the following local bindings
52 ;; in vm, gnus, and rmail:
53 ;;
54 ;; M-l ffap-next, or ffap-gnus-next in gnus
55 ;; M-m ffap-menu, or ffap-gnus-menu in gnus
56 ;;
57 ;; If you do not like these bindings, modify the variable
58 ;; `ffap-bindings', or write your own.
59 ;;
60 ;; If you use ange-ftp, browse-url, complete, efs, or w3, it is best
61 ;; to load or autoload them before ffap. If you use ff-paths, load it
62 ;; afterwards. Try apropos {C-h a ffap RET} to get a list of the many
63 ;; option variables. In particular, if ffap is slow, try these:
64 ;;
65 ;; (setq ffap-alist nil) ; faster, dumber prompting
66 ;; (setq ffap-machine-p-known 'accept) ; no pinging
67 ;; (setq ffap-url-regexp nil) ; disable url features in ffap
68 ;;
69 ;; ffap uses w3 (if found) or else browse-url to fetch url's. For
70 ;; a hairier `ffap-url-fetcher', try ffap-url.el (same ftp site).
71 ;; Also, you can add `ffap-menu-rescan' to various hooks to fontify
72 ;; the file and url references within a buffer.
73
74 ;;; Todo list:
75 ;; * recognize paths inside /usr/bin:/bin:/etc, ./ffap.el:80:
76 ;; * let "/path/file#key" jump to key (offset or regexp) in /path/file
77 ;; * find file of symbol if TAGS is loaded (like above)
78 ;; * break up long menus into multiple panes (like imenu?)
79 ;; * notice node in "(dired)Virtual Dired" (handle the space?)
80 ;; * notice "machine.dom blah blah blah path/file" (how?)
81 ;; * if w3 becomes standard, could rewrite to use its functions
82 ;; * regexp options for ffap-string-at-point, like font-lock (MCOOK)
83 ;; * v19: could replace `ffap-locate-file' with a quieter `locate-library'
84 ;; * support for custom.el
85 ;; + handle "$(HOME)" in Makefiles?
86 ;; + modify `font-lock-keywords' to do fontification
87
88 \f
89 ;;; Code:
90
91 (provide 'ffap)
92
93 ;; Versions: This file is tested with Emacs 19.30. It mostly works
94 ;; with XEmacs, but get ffap-xe.el for the popup menu. Emacs 18 is
95 ;; now abandoned (get ffap-15.el instead).
96
97 (defvar ffap-xemacs (and (string-match "X[Ee]macs" emacs-version) t)
98 "Whether ffap thinks it is running under XEmacs.")
99
100
101 \f
102 ;;; User Variables:
103
104 ;; This function is used inside defvars:
105 (defun ffap-soft-value (name &optional default)
106 "Return value of symbol with NAME, if it is interned.
107 Otherwise return nil (or the optional DEFAULT value)."
108 ;; Bug: (ffap-soft-value "nil" 5) --> 5
109 (let ((sym (intern-soft name)))
110 (if (and sym (boundp sym)) (symbol-value sym) default)))
111
112
113 (defvar ffap-ftp-regexp
114 (and
115 (or (featurep 'ange-ftp)
116 (featurep 'efs)
117 (and (boundp 'file-name-handler-alist) ; v19
118 (or (rassq 'ange-ftp-hook-function file-name-handler-alist)
119 (rassq 'efs-file-handler-function file-name-handler-alist))))
120 ;; Apparently this is good enough for both ange-ftp and efs:
121 "\\`/[^/:]+:")
122 "*Treat paths matching this as remote ftp paths. Nil to disable.
123 Nil also disables the generation of such paths by ffap.")
124
125 (defvar ffap-url-unwrap-local t
126 "*If non-nil, convert \"file:\" url to local path before prompting.")
127
128 (defvar ffap-url-unwrap-remote t
129 "*If non-nil, convert \"ftp:\" url to remote path before prompting.
130 This is ignored if `ffap-ftp-regexp' is nil.")
131
132 (defvar ffap-ftp-default-user
133 (if (or (equal (ffap-soft-value "ange-ftp-default-user") "anonymous")
134 (equal (ffap-soft-value "efs-default-user") "anonymous"))
135 nil
136 "anonymous")
137 "*User name in ftp paths generated by `ffap-host-to-path'.
138 Nil to rely on `efs-default-user' or `ange-ftp-default-user'.")
139
140 (defvar ffap-rfs-regexp
141 ;; Remote file access built into file system? HP rfa or Andrew afs:
142 "\\`/\\(afs\\|net\\)/."
143 ;; afs only: (and (file-exists-p "/afs") "\\`/afs/.")
144 "*Matching paths are treated as remote. Nil to disable.")
145
146 (defvar ffap-url-regexp
147 ;; Could just use `url-nonrelative-link' of w3, if loaded.
148 ;; This regexp is not exhaustive, it just matches common cases.
149 (concat
150 "\\`\\("
151 "news\\(post\\)?:\\|mailto:\\|file:" ; no host ok
152 "\\|"
153 "\\(ftp\\|http\\|telnet\\|gopher\\|www\\|wais\\)://" ; needs host
154 "\\)." ; require one more character
155 )
156 "Regexp matching url's. Nil to disable url features in ffap.")
157
158 (defvar ffap-foo-at-bar-prefix "mailto"
159 "*Presumed url prefix type of strings like \"<foo.9z@bar>\".
160 Sensible values are nil, \"news\", or \"mailto\".")
161
162 \f
163 ;;; Peanut Gallery:
164 ;;
165 ;; Users of ffap occasionally suggest new features. If I consider
166 ;; those features interesting but not clear winners (a matter of
167 ;; personal taste) I try to leave options to enable them. Read
168 ;; through this section for features that you like, put an appropriate
169 ;; enabler in your .emacs file.
170
171 (defvar ffap-dired-wildcards nil ; "[*?][^/]*$"
172 ;; Suggestion from RHOGEE, 07 Jul 1994. Disabled, dired is still
173 ;; available by "C-x C-d <pattern>", and valid filenames may
174 ;; sometimes contain wildcard characters.
175 "*A regexp matching filename wildcard characters, or nil.
176 If `find-file-at-point' gets a filename matching this pattern,
177 it passes it on to `dired' instead of `find-file'.")
178
179 (defvar ffap-newfile-prompt nil ; t
180 ;; Suggestion from RHOGEE, 11 Jul 1994. Disabled, I think this is
181 ;; better handled by `find-file-not-found-hooks'.
182 "*Whether `find-file-at-point' prompts about a nonexistent file.")
183
184 (defvar ffap-require-prefix nil
185 ;; Suggestion from RHOGEE, 20 Oct 1994.
186 "*If set, reverses the prefix argument to `find-file-at-point'.
187 This is nil so neophytes notice ffap. Experts may prefer to disable
188 ffap most of the time.")
189
190 (defvar ffap-file-finder 'find-file
191 "*The command called by `find-file-at-point' to find a file.")
192 (put 'ffap-file-finder 'risky-local-variable t)
193
194 (defvar ffap-url-fetcher
195 (cond ((fboundp 'w3-fetch) 'w3-fetch)
196 ((fboundp 'browse-url-netscape) 'browse-url-netscape)
197 (t 'w3-fetch))
198 ;; Remote control references:
199 ;; http://www.ncsa.uiuc.edu/SDG/Software/XMosaic/remote-control.html
200 ;; http://home.netscape.com/newsref/std/x-remote.html
201 "*A function of one argument, called by ffap to fetch an URL.
202 Reasonable choices are `w3-fetch' or `browse-url-netscape'.
203 For a fancier alternative, get ffap-url.el.")
204 (put 'ffap-url-fetcher 'risky-local-variable t)
205
206 \f
207 ;;; Command ffap-next:
208 ;;
209 ;; Original ffap-next-url (URL's only) from RPECK 30 Mar 1995. Since
210 ;; then, broke it up into ffap-next-guess (noninteractive) and
211 ;; ffap-next (a command). It now work on files as well as url's.
212
213 (defvar ffap-next-regexp
214 ;; If you want ffap-next to find URL's only, try this:
215 ;; (and ffap-url-regexp (string-match "\\\\`" ffap-url-regexp)
216 ;; (concat "\\<" (substring ffap-url-regexp 2))))
217 ;;
218 ;; It pays to put a big fancy regexp here, since ffap-guesser is
219 ;; much more time-consuming than regexp searching:
220 "[/:.~a-zA-Z]/\\|@[a-zA-Z][-a-zA-Z0-9]*\\."
221 "*Regular expression governing movements of `ffap-next'.")
222
223 (defvar ffap-next-guess nil "Last value returned by `ffap-next-guess'.")
224 (defun ffap-next-guess (&optional back lim)
225 "Move point to next file or url, and return it as a string.
226 If nothing is found, leave point at limit and return nil.
227 Optional BACK argument makes search backwards.
228 Optional LIM argument limits the search.
229 Only considers strings that match `ffap-next-regexp'."
230 (or lim (setq lim (if back (point-min) (point-max))))
231 (let (guess)
232 (while (not (or guess (eq (point) lim)))
233 (funcall (if back 're-search-backward 're-search-forward)
234 ffap-next-regexp lim 'move)
235 (setq guess (ffap-guesser)))
236 ;; Go to end, so we do not get same guess twice:
237 (goto-char (nth (if back 0 1) ffap-string-at-point-region))
238 (setq ffap-next-guess guess)))
239
240 ;;;###autoload
241 (defun ffap-next (&optional back wrap)
242 "Search buffer for next file or url, and run ffap.
243 Optional argument BACK says to search backwards.
244 Optional argument WRAP says to try wrapping around if necessary.
245 Interactively: use a single prefix to search backwards,
246 double prefix to wrap forward, triple to wrap backwards.
247 Actual search is done by `ffap-next-guess'."
248 (interactive
249 (cdr (assq (prefix-numeric-value current-prefix-arg)
250 '((1) (4 t) (16 nil t) (64 t t)))))
251 (let ((pt (point))
252 (guess (ffap-next-guess back)))
253 ;; Try wraparound if necessary:
254 (and (not guess) wrap
255 (goto-char (if back (point-max) (point-min)))
256 (setq guess (ffap-next-guess back pt)))
257 (if guess
258 (progn
259 (sit-for 0) ; display point movement
260 (find-file-at-point (ffap-prompter guess)))
261 (goto-char pt) ; restore point
262 (message "No %sfiles or URL's found."
263 (if wrap "" "more ")))))
264
265 (defun ffap-next-url (&optional back wrap)
266 "Like `ffap-next', but search with `ffap-url-regexp'."
267 (interactive)
268 (let ((ffap-next-regexp ffap-url-regexp))
269 (if (interactive-p)
270 (call-interactively 'ffap-next)
271 (ffap-next back wrap))))
272
273 \f
274 ;;; Remote machines and paths:
275
276 (defun ffap-replace-path-component (fullname name)
277 "In remote FULLNAME, replace path with NAME. May return nil."
278 ;; Use ange-ftp or efs if loaded, but do not load them otherwise.
279 (let (found)
280 (mapcar
281 (function (lambda (sym) (and (fboundp sym) (setq found sym))))
282 '(
283 efs-replace-path-component
284 ange-ftp-replace-path-component
285 ange-ftp-replace-name-component
286 ))
287 (and found
288 (fset 'ffap-replace-path-component found)
289 (funcall found fullname name))))
290 ;; (ffap-replace-path-component "/who@foo.com:/whatever" "/new")
291
292 (defun ffap-file-exists-string (file)
293 ;; With certain packages (ange-ftp, jka-compr?) file-exists-p
294 ;; sometimes returns a nicer string than it is given. Otherwise, it
295 ;; just returns nil or t.
296 "Return FILE \(maybe modified\) if it exists, else nil."
297 (and file ; quietly reject nil
298 (let ((exists (file-exists-p file)))
299 (and exists (if (stringp exists) exists file)))))
300
301 ;; I cannot decide a "best" strategy here, so these are variables. In
302 ;; particular, if `Pinging...' is broken or takes too long on your
303 ;; machine, try setting these all to accept or reject.
304 (defvar ffap-machine-p-local 'reject ; this happens often
305 "*A symbol, one of: ping, accept, reject.
306 What `ffap-machine-p' does with hostnames that have no domain.")
307 (defvar ffap-machine-p-known 'ping ; 'accept for speed
308 "*A symbol, one of: ping, accept, reject.
309 What `ffap-machine-p' does with hostnames that have a known domain
310 \(see mail-extr.el for the known domains\).")
311 (defvar ffap-machine-p-unknown 'reject
312 "*A symbol, one of: ping, accept, reject.
313 What `ffap-machine-p' does with hostnames that have an unknown domain
314 \(see mail-extr.el for the known domains\).")
315
316 (defun ffap-what-domain (domain)
317 ;; Like what-domain in mail-extr.el, returns string or nil.
318 (require 'mail-extr)
319 (defvar mail-extr-all-top-level-domains
320 (ffap-soft-value "all-top-level-domains" obarray)) ; XEmacs, old Emacs
321 (get (intern-soft (downcase domain) mail-extr-all-top-level-domains)
322 'domain-name))
323
324 (defun ffap-machine-p (host &optional service quiet strategy)
325 "Decide whether HOST is the name of a real, reachable machine.
326 Depending on the domain (none, known, or unknown), follow the strategy
327 named by the variable `ffap-machine-p-local', `ffap-machine-p-known',
328 or `ffap-machine-p-unknown'. Pinging uses `open-network-stream'.
329 Optional SERVICE specifies the port used \(default \"discard\"\).
330 Optional QUIET flag suppresses the \"Pinging...\" message.
331 Optional STRATEGY overrides the three variables above.
332 Returned values:
333 t means that HOST answered.
334 'accept means the relevant variable told us to accept.
335 \"mesg\" means HOST exists, but does not respond for some reason."
336 ;; Try some (Emory local):
337 ;; (ffap-machine-p "ftp" nil nil 'ping)
338 ;; (ffap-machine-p "nonesuch" nil nil 'ping)
339 ;; (ffap-machine-p "ftp.mathcs.emory.edu" nil nil 'ping)
340 ;; (ffap-machine-p "mathcs" 5678 nil 'ping)
341 ;; (ffap-machine-p "foo.bonk" nil nil 'ping)
342 ;; (ffap-machine-p "foo.bonk.com" nil nil 'ping)
343 (if (or (string-match "[^-a-zA-Z0-9.]" host) ; Illegal chars (?)
344 (not (string-match "[^0-9]" host))) ; 1: a number? 2: quick reject
345 nil
346 (let* ((domain
347 (and (string-match "\\.[^.]*$" host)
348 (downcase (substring host (1+ (match-beginning 0))))))
349 (what-domain (if domain (ffap-what-domain domain) "Local")))
350 (or strategy
351 (setq strategy
352 (cond ((not domain) ffap-machine-p-local)
353 ((not what-domain) ffap-machine-p-unknown)
354 (t ffap-machine-p-known))))
355 (cond
356 ((eq strategy 'accept) 'accept)
357 ((eq strategy 'reject) nil)
358 ;; assume (eq strategy 'ping)
359 (t
360 (or quiet
361 (if (stringp what-domain)
362 (message "Pinging %s (%s)..." host what-domain)
363 (message "Pinging %s ..." host)))
364 (condition-case error
365 (progn
366 (delete-process
367 (open-network-stream
368 "ffap-machine-p" nil host (or service "discard")))
369 t)
370 (error
371 (let ((mesg (car (cdr error))))
372 (cond
373 ;; v18:
374 ((string-match "^Unknown host" mesg) nil)
375 ((string-match "not responding$" mesg) mesg)
376 ;; v19:
377 ;; (file-error "connection failed" "permission denied"
378 ;; "nonesuch" "ffap-machine-p")
379 ;; (file-error "connection failed" "host is unreachable"
380 ;; "gopher.house.gov" "ffap-machine-p")
381 ;; (file-error "connection failed" "address already in use"
382 ;; "ftp.uu.net" "ffap-machine-p")
383 ((equal mesg "connection failed")
384 (if (equal (nth 2 error) "permission denied")
385 nil ; host does not exist
386 ;; Other errors mean the host exists:
387 (nth 2 error)))
388 ;; Could be "Unknown service":
389 (t (signal (car error) (cdr error))))))))))))
390
391 (defun ffap-file-remote-p (filename)
392 "If FILENAME looks remote, return it \(maybe slightly improved\)."
393 ;; (ffap-file-remote-p "/user@foo.bar.com:/pub")
394 ;; (ffap-file-remote-p "/cssun.mathcs.emory.edu://path")
395 ;; (ffap-file-remote-p "/ffap.el:80")
396 (or (and ffap-ftp-regexp
397 (string-match ffap-ftp-regexp filename)
398 ;; Convert "/host.com://path" to "/host:/path", to handle a dieing
399 ;; practice of advertising ftp paths as "host.dom://path".
400 (if (string-match "//" filename)
401 ;; (replace-match "/" nil nil filename)
402 (concat (substring filename 0 (1+ (match-beginning 0)))
403 (substring filename (match-end 0)))
404 filename))
405 (and ffap-rfs-regexp
406 (string-match ffap-rfs-regexp filename)
407 filename)))
408
409 (defun ffap-machine-at-point nil
410 "Return machine name at point if it exists, or nil."
411 (let ((mach (ffap-string-at-point 'machine)))
412 (and (ffap-machine-p mach) mach)))
413
414 (defsubst ffap-host-to-path (host)
415 "Convert HOST to something like \"/anonymous@HOST:\".
416 Looks at `ffap-ftp-default-user', returns \"\" for \"localhost\"."
417 (if (equal host "localhost") ""
418 (concat "/"
419 ffap-ftp-default-user (and ffap-ftp-default-user "@")
420 host ":")))
421
422 (defun ffap-fixup-machine (mach)
423 ;; Convert a hostname into an url, an ftp path, or nil.
424 (cond
425 ((not (and ffap-url-regexp (stringp mach))) nil)
426 ;; gopher.well.com
427 ((string-match "\\`gopher[-.]" mach) ; or "info"?
428 (concat "gopher://" mach "/"))
429 ;; www.ncsa.uiuc.edu
430 ((and (string-match "\\`w\\(ww\\|eb\\)[-.]" mach))
431 (concat "http://" mach "/"))
432 ;; More cases? Maybe "telnet:" for archie?
433 (ffap-ftp-regexp (ffap-host-to-path mach))
434 ))
435
436 (defun ffap-newsgroup-p (string)
437 "Return STRING if it looks like a newsgroup name, else nil."
438 (and
439 (string-match ffap-newsgroup-regexp string)
440 (let ((htbs '(gnus-active-hashtb gnus-newsrc-hashtb gnus-killed-hashtb))
441 (heads ffap-newsgroup-heads)
442 htb ret)
443 (while htbs
444 (setq htb (car htbs) htbs (cdr htbs))
445 (condition-case nil
446 (progn
447 ;; errs: htb symbol may be unbound, or not a hash-table.
448 ;; gnus-gethash is just a macro for intern-soft.
449 (and (intern-soft string (symbol-value htb))
450 (setq ret string htbs nil))
451 ;; If we made it this far, gnus is running, so ignore "heads":
452 (setq heads nil))
453 (error nil)))
454 (or ret (not heads)
455 (let ((head (string-match "\\`\\([a-z]+\\)\\." string)))
456 (and head (setq head (substring string 0 (match-end 1)))
457 (member head heads)
458 (setq ret string))))
459 ;; Is there ever a need to modify string as a newsgroup name?
460 ret)))
461 (defvar ffap-newsgroup-regexp "^[a-z]+\\.[-+a-z_0-9.]+$"
462 "Strings not matching this fail `ffap-newsgroup-p'.")
463 (defvar ffap-newsgroup-heads ; entirely inadequate
464 '("alt" "comp" "gnu" "misc" "news" "sci" "soc" "talk")
465 "Used by `ffap-newsgroup-p' if gnus is not running.")
466
467 (defsubst ffap-url-p (string)
468 "If STRING looks like an url, return it (maybe improved), else nil."
469 (let ((case-fold-search t))
470 (and ffap-url-regexp (string-match ffap-url-regexp string)
471 ;; I lied, no improvement:
472 string)))
473
474 ;; Broke these out of ffap-fixup-url, for use of ffap-url package.
475 (defsubst ffap-url-unwrap-local (url)
476 "Return URL as a local file, or nil. Ignores `ffap-url-regexp'."
477 (and (string-match "\\`\\(file\\|ftp\\):/?\\([^/]\\|\\'\\)" url)
478 (substring url (1+ (match-end 1)))))
479 (defsubst ffap-url-unwrap-remote (url)
480 "Return URL as a remote file, or nil. Ignores `ffap-url-regexp'."
481 (and (string-match "\\`\\(ftp\\|file\\)://\\([^:/]+\\):?\\(/.*\\)" url)
482 (concat
483 (ffap-host-to-path (substring url (match-beginning 2) (match-end 2)))
484 (substring url (match-beginning 3) (match-end 3)))))
485 ;; Test: (ffap-url-unwrap-remote "ftp://foo.com/bar.boz")
486
487 (defun ffap-fixup-url (url)
488 "Clean up URL and return it, maybe as a file name."
489 (cond
490 ((not (stringp url)) nil)
491 ((and ffap-url-unwrap-local (ffap-url-unwrap-local url)))
492 ((and ffap-url-unwrap-remote ffap-ftp-regexp
493 (ffap-url-unwrap-remote url)))
494 ;; Do not load w3 just for this:
495 (t (let ((normal (and (fboundp 'url-normalize-url)
496 (url-normalize-url url))))
497 ;; In case url-normalize-url is confused:
498 (or (and normal (not (zerop (length normal))) normal)
499 url)))))
500
501 \f
502 ;;; `ffap-alist':
503 ;;
504 ;; Search actions depending on the major-mode or extensions of the
505 ;; current name. Note all the little defun's could be broken out, at
506 ;; some loss of locality. A good example of featuritis.
507
508 ;; First, some helpers for functions in `ffap-alist':
509
510 (defvar path-separator ":") ; for XEmacs 19.13
511
512 (defun ffap-list-env (env &optional empty)
513 ;; Replace this with parse-colon-path (lisp/files.el)?
514 "Directory list parsed from path envinronment variable ENV.
515 Optional EMPTY is default if (getenv ENV) is undefined, and is also
516 substituted for the first empty-string component, if there is one.
517 Uses `path-separator' to separate the path into directories."
518 ;; Derived from psg-list-env in RHOGEE's ff-paths and
519 ;; bib-cite packages. The `empty' argument is intended to mimic
520 ;; the semantics of TeX/BibTeX variables, it is substituted for
521 ;; any empty string entry.
522 (if (or empty (getenv env)) ; should return something
523 (let ((start 0) match dir ret)
524 (setq env (concat (getenv env) path-separator))
525 (while (setq match (string-match path-separator env start))
526 (setq dir (substring env start match) start (1+ match))
527 ;;(and (file-directory-p dir) (not (member dir ret)) ...)
528 (setq ret (cons dir ret)))
529 (setq ret (nreverse ret))
530 (and empty (setq match (member "" ret))
531 (progn
532 (setcdr match (append (cdr-safe empty) (cdr match)))
533 (setcar match (or (car-safe empty) empty))))
534 ret)))
535
536 (defun ffap-reduce-path (path)
537 "Remove duplicates and non-directories from PATH list."
538 (let (ret tem)
539 (while path
540 (setq tem path path (cdr path))
541 (if (equal (car tem) ".") (setcar tem ""))
542 (or (member (car tem) ret)
543 (not (file-directory-p (car tem)))
544 (progn (setcdr tem ret) (setq ret tem))))
545 (nreverse ret)))
546
547 (defun ffap-add-subdirs (path)
548 "Return PATH augmented with its immediate subdirectories."
549 ;; (ffap-add-subdirs '("/notexist" "~"))
550 (let (ret subs)
551 (while path
552 (mapcar
553 (function
554 (lambda (f) (and (file-directory-p f) (setq ret (cons f ret)))))
555 (condition-case nil
556 (directory-files (car path) t "[^.]")
557 (error nil)))
558 (setq ret (cons (car path) ret)
559 path (cdr path)))
560 (nreverse ret)))
561
562 (defvar ffap-alist
563 ;; A big mess! Parts are probably useless.
564 (list
565 (cons "\\.info\\'"
566 (defun ffap-info (name)
567 (locate-library
568 name '("" ".info")
569 (or (ffap-soft-value "Info-directory-list")
570 (ffap-soft-value "Info-default-directory-list")
571 ;; v18:
572 (list (ffap-soft-value "Info-directory" "~/info/"))))))
573 ;; Since so many info files do not have .info extension, also do this:
574 (cons "\\`info/"
575 (defun ffap-info-2 (name) (ffap-info (substring name 5))))
576 (cons "\\`[-a-z]+\\'"
577 ;; This ignores the node! "(emacs)Top" same as "(emacs)Intro"
578 (defun ffap-info-3 (name)
579 (and (equal (ffap-string-around) "()") (ffap-info name))))
580 (cons "\\.elc?\\'"
581 (defun ffap-el (name) (locate-library name t)))
582 (cons 'emacs-lisp-mode
583 (defun ffap-el-mode (name)
584 ;; We do not bother with "" here, since it was considered above.
585 ;; Also ignore "elc", for speed (who else reads elc files?)
586 (and (not (string-match "\\.el\\'" name))
587 (locate-library name '(".el")))))
588 '(finder-mode . ffap-el-mode) ; v19: {C-h p}
589 '(help-mode . ffap-el-mode) ; v19.29
590 (cons 'c-mode
591 (progn
592 ;; Need better defaults here!
593 (defvar ffap-c-path '("/usr/include" "/usr/local/include"))
594 (defun ffap-c-mode (name)
595 (locate-library name t ffap-c-path))))
596 '(c++-mode . ffap-c-mode)
597 '(cc-mode . ffap-c-mode)
598 '("\\.\\([chCH]\\|cc\\|hh\\)\\'" . ffap-c-mode)
599 (cons 'tex-mode
600 ;; Complicated because auctex may not be loaded yet.
601 (progn
602 (defvar ffap-tex-path
603 t ; delayed initialization
604 "Path where `ffap-tex-mode' looks for tex files.
605 If t, `ffap-tex-init' will initialize this when needed.")
606 (defun ffap-tex-init nil
607 ;; Compute ffap-tex-path if it is now t.
608 (and (eq t ffap-tex-path)
609 (message "Initializing ffap-tex-path ...")
610 (setq ffap-tex-path
611 (ffap-reduce-path
612 (append
613 (list ".")
614 (ffap-list-env "TEXINPUTS")
615 ;; (ffap-list-env "BIBINPUTS")
616 (ffap-add-subdirs
617 (ffap-list-env "TEXINPUTS_SUBDIR"
618 (ffap-soft-value
619 "TeX-macro-global"
620 '("/usr/local/lib/tex/macros"
621 "/usr/local/lib/tex/inputs")
622 ))))))))
623 (defun ffap-tex-mode (name)
624 (ffap-tex-init)
625 (locate-library name '(".tex" "") ffap-tex-path))))
626 (cons 'latex-mode
627 (defun ffap-latex-mode (name)
628 (ffap-tex-init)
629 ;; Any real need for "" here?
630 (locate-library name '(".cls" ".sty" ".tex" "")
631 ffap-tex-path)))
632 (cons "\\.\\(tex\\|sty\\|doc\\|cls\\)\\'"
633 (defun ffap-tex (name)
634 (ffap-tex-init)
635 (locate-library name t ffap-tex-path)))
636 (cons "\\.bib\\'"
637 (defun ffap-bib (name)
638 (locate-library
639 name t
640 (ffap-list-env "BIBINPUTS" '("/usr/local/lib/tex/macros/bib")))))
641 (cons 'math-mode
642 (defun ffap-math-mode (name)
643 (while (string-match "`" name)
644 (setq name (concat (substring name 0 (match-beginning 0))
645 "/"
646 (substring name (match-end 0)))))
647 (locate-library
648 name '(".m" "") (ffap-soft-value "Mathematica-search-path"))))
649 (cons "\\`\\." (defun ffap-home (name) (locate-library name t '("~"))))
650 (cons "\\`~/"
651 ;; Maybe a "Lisp Code Directory" reference:
652 (defun ffap-lcd (name)
653 (and
654 (or
655 ;; lisp-dir-apropos output buffer:
656 (string-match "Lisp Code Dir" (buffer-name))
657 ;; Inside an LCD entry like |~/misc/ffap.el.Z|,
658 ;; or maybe the holy LCD-Datafile itself:
659 (member (ffap-string-around) '("||" "|\n")))
660 (concat
661 ;; lispdir.el may not be loaded yet:
662 (ffap-host-to-path
663 (ffap-soft-value "elisp-archive-host"
664 "archive.cis.ohio-state.edu"))
665 (file-name-as-directory
666 (ffap-soft-value "elisp-archive-directory"
667 "/pub/gnu/emacs/elisp-archive/"))
668 (substring name 2)))))
669 (cons "^[Rr][Ff][Cc][- #]?\\([0-9]+\\)" ; no $
670 (progn
671 (defvar ffap-rfc-path
672 (concat (ffap-host-to-path "ds.internic.net") "/rfc/rfc%s.txt"))
673 (defun ffap-rfc (name)
674 (format ffap-rfc-path
675 (substring name (match-beginning 1) (match-end 1))))))
676 (cons "\\`[^/]*\\'"
677 (defun ffap-dired (name)
678 (let ((pt (point)) dir try)
679 (save-excursion
680 (and (progn
681 (beginning-of-line)
682 (looking-at " *[-d]r[-w][-x][-r][-w][-x][-r][-w][-x] "))
683 (re-search-backward "^ *$" nil t)
684 (re-search-forward "^ *\\([^ \t\n:]*\\):\n *total " pt t)
685 (file-exists-p
686 (setq try
687 (expand-file-name
688 name
689 (buffer-substring
690 (match-beginning 1) (match-end 1)))))
691 try)))))
692 )
693 "Alist of \(KEY . FUNCTION\) pairs parsed by `ffap-file-at-point'.
694 If string NAME at point (maybe \"\") is not a file or url, these pairs
695 specify actions to try creating such a string. A pair matches if either
696 KEY is a symbol, and it equals `major-mode', or
697 KEY is a string, it should matches NAME as a regexp.
698 On a match, \(FUNCTION NAME\) is called and should return a file, an
699 url, or nil. If nil, search the alist for further matches.")
700
701 (put 'ffap-alist 'risky-local-variable t)
702
703 \f
704 ;;; At-Point Functions:
705
706 (defvar ffap-string-at-point-mode-alist
707 '(
708 ;; The default, used when the `major-mode' is not found.
709 ;; Slightly controversial decisions:
710 ;; * strip trailing "@" and ":"
711 ;; * no commas (good for latex)
712 (file "--:$+<>@-Z_a-z~" "<@" "@>;.,!?:")
713 ;; An url, or maybe a email/news message-id:
714 (url "--:?$+@-Z_a-z~#,%" "^A-Za-z0-9" ":;.,!?")
715 ;; Find a string that does *not* contain a colon:
716 (nocolon "--9$+<>@-Z_a-z~" "<@" "@>;.,!?")
717 ;; A machine:
718 (machine "-a-zA-Z0-9." "" ".")
719 ;; Mathematica paths: allow backquotes
720 (math-mode ",-:$+<>@-Z_a-z~`" "<" "@>;.,!?`:")
721 )
722 "Alist of \(MODE CHARS BEG END\), where MODE is a symbol,
723 possibly a `major-mode' or some symbol internal to ffap
724 \(such as 'file, 'url, 'machine, and 'nocolon\).
725 `ffap-string-at-point' uses the data fields as follows:
726 1. find a maximal string of CHARS around point,
727 2. strip BEG chars before point from the beginning,
728 3. Strip END chars after point from the end.")
729
730 (defvar ffap-string-at-point-region '(1 1)
731 "List (BEG END), last region returned by `ffap-string-at-point'.")
732
733 (defvar ffap-string-at-point nil
734 ;; Added at suggestion of RHOGEE (for ff-paths), 7/24/95.
735 "Last string returned by `ffap-string-at-point'.")
736
737 (defun ffap-string-at-point (&optional mode)
738 "Return a string of characters from around point.
739 MODE (defaults to `major-mode') is a symbol used to lookup string
740 syntax parameters in `ffap-string-at-point-mode-alist'.
741 If MODE is not found, we fall back on the symbol 'file.
742 Sets `ffap-string-at-point' and `ffap-string-at-point-region'."
743 (let* ((args
744 (cdr
745 (or (assq (or mode major-mode) ffap-string-at-point-mode-alist)
746 (assq 'file ffap-string-at-point-mode-alist))))
747 (pt (point))
748 (str
749 (buffer-substring
750 (save-excursion
751 (skip-chars-backward (car args))
752 (skip-chars-forward (nth 1 args) pt)
753 (setcar ffap-string-at-point-region (point)))
754 (save-excursion
755 (skip-chars-forward (car args))
756 (skip-chars-backward (nth 2 args) pt)
757 (setcar (cdr ffap-string-at-point-region) (point))))))
758 (or ffap-xemacs (set-text-properties 0 (length str) nil str))
759 (setq ffap-string-at-point str)))
760
761 (defun ffap-string-around nil
762 ;; Sometimes useful to decide how to treat a string.
763 "Return string of two chars around last `ffap-string-at-point'.
764 Assumes the buffer has not changed."
765 (save-excursion
766 (format "%c%c"
767 (progn
768 (goto-char (car ffap-string-at-point-region))
769 (preceding-char)) ; maybe 0
770 (progn
771 (goto-char (nth 1 ffap-string-at-point-region))
772 (following-char)) ; maybe 0
773 )))
774
775 (defun ffap-copy-string-as-kill (&optional mode)
776 ;; Requested by MCOOK. Useful?
777 "Call `ffap-string-at-point', and copy result to `kill-ring'."
778 (interactive)
779 (let ((str (ffap-string-at-point mode)))
780 (if (equal "" str)
781 (message "No string found around point.")
782 (kill-new str)
783 ;; Older: (apply 'copy-region-as-kill ffap-string-at-point-region)
784 (message "Copied to kill ring: %s" str))))
785
786 (defun ffap-url-at-point nil
787 "Return url from around point if it exists, or nil."
788 ;; Could use w3's url-get-url-at-point instead. Both handle "URL:",
789 ;; ignore non-relative links, trim punctuation. The other will
790 ;; actually look back if point is in whitespace, but I would rather
791 ;; ffap be non-rabid in such situations.
792 (and
793 ffap-url-regexp
794 (or
795 ;; In a w3 buffer button zone?
796 (let (tem)
797 (and (eq major-mode 'w3-mode)
798 ;; assume: (boundp 'w3-zone-at) (boundp 'w3-zone-data)
799 (setq tem (w3-zone-at (point)))
800 (consp (setq tem (w3-zone-data tem)))
801 (nth 2 tem)))
802 ;; Is there a reason not to strip trailing colon?
803 (let ((name (ffap-string-at-point 'url)))
804 ;; (case-fold-search t), why?
805 (cond
806 ((string-match "^url:" name) (setq name (substring name 4)))
807 ((and (string-match "\\`[^:</>@]+@[^:</>@]+[a-zA-Z]\\'" name)
808 ;; "foo@bar": could be "mailto" or "news" (a Message-ID).
809 ;; If not adorned with "<>", it must be "mailto".
810 ;; Otherwise could be either, so consult `ffap-foo-at-bar-prefix'.
811 (let ((prefix (if (and (equal (ffap-string-around) "<>")
812 ;; At least a couple of odd characters:
813 (string-match "[$.0-9].*[$.0-9].*@" name))
814 ;; Could be news:
815 ffap-foo-at-bar-prefix
816 "mailto")))
817 (and prefix (setq name (concat prefix ":" name))))))
818 ((ffap-newsgroup-p name) (setq name (concat "news:" name)))
819 ((and (string-match "\\`[a-z0-9]+\\'" name) ; <mic> <root> <nobody>
820 (equal (ffap-string-around) "<>")
821 ;; (ffap-user-p name):
822 (not (string-match "~" (expand-file-name (concat "~" name))))
823 )
824 (setq name (concat "mailto:" name)))
825 )
826 (and (ffap-url-p name) name)
827 ))))
828
829 (defvar ffap-gopher-regexp
830 "^.*\\<\\(Type\\|Name\\|Path\\|Host\\|Port\\) *= *\\(.*\\) *$"
831 "Regexp Matching a line in a gopher bookmark (maybe indented).
832 The two subexpressions are the KEY and VALUE.")
833
834 (defun ffap-gopher-at-point nil
835 "If point is inside a gopher bookmark block, return its url."
836 ;; `gopher-parse-bookmark' from gopher.el is not so robust
837 (save-excursion
838 (beginning-of-line)
839 (if (looking-at ffap-gopher-regexp)
840 (progn
841 (while (and (looking-at ffap-gopher-regexp) (not (bobp)))
842 (forward-line -1))
843 (or (looking-at ffap-gopher-regexp) (forward-line 1))
844 (let ((type "1") name path host (port "70"))
845 (while (looking-at ffap-gopher-regexp)
846 (let ((var (intern
847 (downcase
848 (buffer-substring (match-beginning 1)
849 (match-end 1)))))
850 (val (buffer-substring (match-beginning 2)
851 (match-end 2))))
852 (set var val)
853 (forward-line 1)))
854 (if (and path (string-match "^ftp:.*@" path))
855 (concat "ftp://"
856 (substring path 4 (1- (match-end 0)))
857 (substring path (match-end 0)))
858 (and (= (length type) 1)
859 host;; (ffap-machine-p host)
860 (concat "gopher://" host
861 (if (equal port "70") "" (concat ":" port))
862 "/" type path))))))))
863
864 (defvar ffap-ftp-sans-slash-regexp
865 (and
866 ffap-ftp-regexp
867 ;; Note: by now, we know it is not an url.
868 ;; Icky regexp avoids: default: 123: foo::bar cs:pub
869 ;; It does match on: mic@cs: cs:/pub mathcs.emory.edu: (point at end)
870 "\\`\\([^:@]+@[^:@]+:\\|[^@.:]+\\.[^@:]+:\\|[^:]+:[~/]\\)\\([^:]\\|\\'\\)")
871 "Strings matching this are coerced to ftp paths by ffap.
872 That is, ffap just prepends \"/\". Set to nil to disable.")
873
874 (defun ffap-file-at-point nil
875 "Return filename from around point if it exists, or nil.
876 Existence test is skipped for names that look remote.
877 If the filename is not obvious, it also tries `ffap-alist',
878 which may actually result in an url rather than a filename."
879 ;; Note: this function does not need to look for url's, just
880 ;; filenames. On the other hand, it is responsible for converting
881 ;; a pseudo-url "site.com://path" to an ftp path
882 (let* ((case-fold-search t) ; url prefixes are case-insensitive
883 (data (match-data))
884 (string (ffap-string-at-point)) ; uses mode alist
885 (name
886 (or (condition-case nil
887 (and (not (string-match "//" string)) ; foo.com://bar
888 (substitute-in-file-name string))
889 (error nil))
890 string))
891 (abs (file-name-absolute-p name))
892 (default-directory default-directory))
893 (unwind-protect
894 (cond
895 ;; Immediate rejects (/ and // are too common in C++):
896 ((member name '("" "/" "//")) nil)
897 ;; Immediately test local filenames. If default-directory is
898 ;; remote, you probably already have a connection.
899 ((and (not abs) (ffap-file-exists-string name)))
900 ;; Accept remote names without actual checking (too slow):
901 ((if abs
902 (ffap-file-remote-p name)
903 ;; Try adding a leading "/" (common omission in ftp paths):
904 (and
905 ffap-ftp-sans-slash-regexp
906 (string-match ffap-ftp-sans-slash-regexp name)
907 (ffap-file-remote-p (concat "/" name)))))
908 ;; Ok, not remote, try the existence test even if it is absolute:
909 ((and abs (ffap-file-exists-string name)))
910 ;; If it contains a colon, get rid of it (and return if exists)
911 ((and (string-match path-separator name)
912 (setq name (ffap-string-at-point 'nocolon))
913 (ffap-file-exists-string name)))
914 ;; File does not exist, try the alist:
915 ((let ((alist ffap-alist) tem try case-fold-search)
916 (while (and alist (not try))
917 (setq tem (car alist) alist (cdr alist))
918 (if (or (eq major-mode (car tem))
919 (and (stringp (car tem))
920 (string-match (car tem) name)))
921 (and (setq try (funcall (cdr tem) name))
922 (setq try (or
923 (ffap-url-p try) ; not a file!
924 (ffap-file-remote-p try)
925 (ffap-file-exists-string try))))))
926 try))
927 ;; Alist failed? Try to guess an active remote connection
928 ;; from buffer variables, and try once more, both as an
929 ;; absolute and relative path on that remote host.
930 ((let* (ffap-rfs-regexp ; suppress
931 (remote-dir
932 (cond
933 ((ffap-file-remote-p default-directory))
934 ((and (eq major-mode 'internal-ange-ftp-mode)
935 (string-match "^\\*ftp \\(.*\\)@\\(.*\\)\\*$"
936 (buffer-name)))
937 (concat "/" (substring (buffer-name) 5 -1) ":"))
938 ;; This is too often a bad idea:
939 ;;((and (eq major-mode 'w3-mode)
940 ;; (stringp url-current-server))
941 ;; (host-to-ange-path url-current-server))
942 )))
943 (and remote-dir
944 (or
945 (and (string-match "\\`\\(/?~?ftp\\)/" name)
946 (ffap-file-exists-string
947 (ffap-replace-path-component
948 remote-dir (substring name (match-end 1)))))
949 (ffap-file-exists-string
950 (ffap-replace-path-component remote-dir name))))))
951 )
952 (store-match-data data))))
953
954 \f
955 ;;; ffap-read-file-or-url:
956 ;;
957 ;; We want to complete filenames as in read-file-name, but also url's
958 ;; which read-file-name-internal would truncate at the "//" string.
959 ;; The solution here is to replace read-file-name-internal with
960 ;; `ffap-read-file-or-url-internal', which checks the minibuffer
961 ;; contents before attempting to complete filenames.
962
963 (defun ffap-read-file-or-url (prompt guess)
964 "Read file or url from minibuffer, with PROMPT and initial GUESS."
965 (or guess (setq guess default-directory))
966 (let (dir)
967 ;; Tricky: guess may have or be a local directory, like "w3/w3.elc"
968 ;; or "w3/" or "../el/ffap.el" or "../../../"
969 (or (ffap-url-p guess)
970 (progn
971 (or (ffap-file-remote-p guess)
972 (setq guess (abbreviate-file-name (expand-file-name guess))))
973 (setq dir (file-name-directory guess))))
974 (setq guess
975 (completing-read
976 prompt
977 'ffap-read-file-or-url-internal
978 dir
979 nil
980 (if dir (cons guess (length dir)) guess)
981 (list 'file-name-history)
982 ))
983 ;; Do file substitution like (interactive "F"), suggested by MCOOK.
984 (or (ffap-url-p guess) (setq guess (substitute-in-file-name guess)))
985 ;; Should not do it on url's, where $ is a common (VMS?) character.
986 ;; Note: upcoming url.el package ought to handle this automatically.
987 guess))
988
989 (defun ffap-read-url-internal (string dir action)
990 "Complete url's from history, treating given string as valid."
991 (let ((hist (ffap-soft-value "url-global-history-hash-table")))
992 (cond
993 ((not action)
994 (or (try-completion string hist) string))
995 ((eq action t)
996 (or (all-completions string hist) (list string)))
997 ;; action == lambda, documented where? Tests whether string is a
998 ;; valid "match". Let us always say yes.
999 (t t))))
1000
1001 (defun ffap-read-file-or-url-internal (string dir action)
1002 (if (ffap-url-p string)
1003 (ffap-read-url-internal string dir action)
1004 (read-file-name-internal string dir action)))
1005
1006 ;; The rest of this page is just to work with package complete.el.
1007 ;; This code assumes that you load ffap.el after complete.el.
1008 ;;
1009 ;; We must inform complete about whether our completion function
1010 ;; will do filename style completion. For earlier versions of
1011 ;; complete.el, this requires a defadvice. For recent versions
1012 ;; there may be a special variable for this purpose.
1013
1014 (defun ffap-complete-as-file-p nil
1015 ;; Will `minibuffer-completion-table' complete the minibuffer
1016 ;; contents as a filename? Assumes the minibuffer is current.
1017 ;; Note: t and non-nil mean somewhat different reasons.
1018 (if (eq minibuffer-completion-table 'ffap-read-file-or-url-internal)
1019 (not (ffap-url-p (buffer-string))) ; t
1020 (memq minibuffer-completion-table
1021 '(read-file-name-internal read-directory-name-internal)) ; list
1022 ))
1023
1024 (and
1025 (featurep 'complete)
1026 (if (boundp 'PC-completion-as-file-name-predicate)
1027 ;; modern version of complete.el, just set the variable:
1028 (setq PC-completion-as-file-name-predicate 'ffap-complete-as-file-p)
1029 (require 'advice)
1030 (defadvice PC-do-completion (around ffap-fix act)
1031 "Work with ffap."
1032 (let ((minibuffer-completion-table
1033 (if (eq t (ffap-complete-as-file-p))
1034 'read-file-name-internal
1035 minibuffer-completion-table)))
1036 ad-do-it))))
1037
1038 \f
1039 ;;; Highlighting:
1040 ;;
1041 ;; Based on overlay highlighting in Emacs 19.28 isearch.el.
1042
1043 (defvar ffap-highlight (and window-system t)
1044 "If non-nil, ffap highlights the current buffer substring.")
1045
1046 (defvar ffap-highlight-overlay nil "Overlay used by `ffap-highlight'.")
1047
1048 (defun ffap-highlight (&optional remove)
1049 "If `ffap-highlight' is set, highlight the guess in this buffer.
1050 That is, the last buffer substring found by `ffap-string-at-point'.
1051 Optional argument REMOVE means to remove any such highlighting.
1052 Uses the face `ffap' if it is defined, or else `highlight'."
1053 (cond
1054 (remove (and ffap-highlight-overlay (delete-overlay ffap-highlight-overlay)))
1055 ((not ffap-highlight) nil)
1056 (ffap-highlight-overlay
1057 (move-overlay ffap-highlight-overlay
1058 (car ffap-string-at-point-region)
1059 (nth 1 ffap-string-at-point-region)
1060 (current-buffer)))
1061 (t
1062 (setq ffap-highlight-overlay (apply 'make-overlay ffap-string-at-point-region))
1063 (overlay-put ffap-highlight-overlay 'face
1064 (if (internal-find-face 'ffap nil)
1065 'ffap 'highlight)))))
1066
1067 \f
1068 ;;; The big enchilada:
1069
1070 (defun ffap-guesser nil
1071 "Return file or url or nil, guessed from text around point."
1072 (or (and ffap-url-regexp
1073 (ffap-fixup-url (or (ffap-url-at-point)
1074 (ffap-gopher-at-point))))
1075 (ffap-file-at-point) ; may yield url!
1076 (ffap-fixup-machine (ffap-machine-at-point))))
1077
1078 (defun ffap-prompter (&optional guess)
1079 ;; Does guess and prompt step for find-file-at-point.
1080 ;; Extra complication for the temporary highlighting.
1081 (unwind-protect
1082 (ffap-read-file-or-url
1083 (if ffap-url-regexp "Find file or URL: " "Find file: ")
1084 (prog1
1085 (setq guess (or guess (ffap-guesser)))
1086 (and guess (ffap-highlight))
1087 ))
1088 (ffap-highlight t)))
1089
1090 ;;;###autoload
1091 (defun find-file-at-point (&optional filename)
1092 "Find FILENAME (or url), guessing default from text around point.
1093 If `ffap-dired-wildcards' is set, wildcard patterns are passed to dired.
1094 See also the functions `ffap-file-at-point', `ffap-url-at-point'.
1095 With a prefix, this command behaves *exactly* like `ffap-file-finder'.
1096 If `ffap-require-prefix' is set, the prefix meaning is reversed.
1097
1098 See <ftp://ftp.mathcs.emory.edu/pub/mic/emacs/> for latest version."
1099 (interactive)
1100 (if (and (interactive-p)
1101 (if ffap-require-prefix (not current-prefix-arg)
1102 current-prefix-arg))
1103 ;; Do exactly the ffap-file-finder command, even the prompting:
1104 (let (current-prefix-arg) ; we already interpreted it
1105 (call-interactively ffap-file-finder))
1106 (or filename (setq filename (ffap-prompter)))
1107 (cond
1108 ((ffap-url-p filename)
1109 (let (current-prefix-arg) ; w3 2.3.25 bug, reported by KPC
1110 (funcall ffap-url-fetcher filename)))
1111 ;; This junk more properly belongs in a modified ffap-file-finder:
1112 ((and ffap-dired-wildcards
1113 (string-match ffap-dired-wildcards filename))
1114 (dired filename))
1115 ((or (not ffap-newfile-prompt)
1116 (file-exists-p filename)
1117 (y-or-n-p "File does not exist, create buffer? "))
1118 (funcall ffap-file-finder
1119 ;; expand-file-name fixes "~/~/.emacs" bug sent by CHUCKR.
1120 (expand-file-name filename)))
1121 ;; User does not want to find a non-existent file:
1122 ((signal 'file-error (list "Opening file buffer"
1123 "no such file or directory"
1124 filename))))))
1125
1126 ;; M-x shortcut:
1127 ;;###autoload
1128 (defalias 'ffap 'find-file-at-point)
1129
1130 \f
1131 ;;; Menu support:
1132 ;;
1133 ;; Bind ffap-menu to a key if you want, since it also works in tty mode.
1134 ;; Or just use it through the ffap-at-mouse binding (next section).
1135
1136 (defvar ffap-menu-regexp nil
1137 "*If non-nil, overrides `ffap-next-regexp' during `ffap-menu'.
1138 Make this more restrictive for faster menu building.
1139 For example, try \":/\" for url (and some ftp) references.")
1140
1141 (defvar ffap-menu-alist nil
1142 "Buffer local cache of menu presented by `ffap-menu'.")
1143 (make-variable-buffer-local 'ffap-menu-alist)
1144
1145 (defvar ffap-menu-text-plist
1146 (and window-system
1147 ;; These choices emulate goto-addr:
1148 (if ffap-xemacs
1149 '(face bold highlight t) ; keymap <map>
1150 '(face bold mouse-face highlight) ; keymap <mousy-map>
1151 ))
1152 "Text properties applied to strings found by `ffap-menu-rescan'.
1153 These properties may be used to fontify the menu references.")
1154
1155 ;;;###autoload
1156 (defun ffap-menu (&optional rescan)
1157 "Put up a menu of files and urls mentioned in this buffer.
1158 Then set mark, jump to choice, and try to fetch it. The menu is
1159 cached in `ffap-menu-alist', and rebuilt by `ffap-menu-rescan'.
1160 The optional RESCAN argument \(a prefix, interactively\) forces
1161 a rebuild. Searches with `ffap-menu-regexp'."
1162 (interactive "P")
1163 ;; (require 'imenu) -- no longer used, but roughly emulated
1164 (if (or (not ffap-menu-alist) rescan
1165 ;; or if the first entry is wrong:
1166 (and ffap-menu-alist
1167 (let ((first (car ffap-menu-alist)))
1168 (save-excursion
1169 (goto-char (cdr first))
1170 (not (equal (car first) (ffap-guesser)))))))
1171 (ffap-menu-rescan))
1172 ;; Tail recursive:
1173 (ffap-menu-ask
1174 (if ffap-url-regexp "Find file or URL" "Find file")
1175 (cons (cons "*Rescan Buffer*" -1) ffap-menu-alist)
1176 'ffap-menu-cont))
1177
1178 (defun ffap-menu-cont (choice) ; continuation of ffap-menu
1179 (if (< (cdr choice) 0)
1180 (ffap-menu t) ; *Rescan*
1181 (push-mark)
1182 (goto-char (cdr choice))
1183 ;; Momentary highlight:
1184 (unwind-protect
1185 (progn
1186 (and ffap-highlight (ffap-guesser) (ffap-highlight))
1187 (sit-for 0) ; display
1188 (find-file-at-point (car choice)))
1189 (ffap-highlight t))))
1190
1191 (defun ffap-menu-ask (title alist cont)
1192 "Prompt from a menu of choices, and then apply some action.
1193 Arguments are TITLE, ALIST, and CONT (a continuation).
1194 This uses either a menu or the minibuffer depending on invocation.
1195 The TITLE string is used as either the prompt or menu title.
1196 Each \(string . data\) ALIST entry defines a choice \(data is ignored\).
1197 Once the user makes a choice, function CONT is applied to the entry.
1198 Always returns nil."
1199 ;; Bug: minibuffer prompting assumes the strings are unique.
1200 (let ((choice
1201 (if (and (fboundp 'x-popup-menu) ; Emacs 19 or XEmacs 19.13
1202 (boundp 'last-nonmenu-event) ; not in XEmacs 19.13
1203 (listp last-nonmenu-event))
1204 (x-popup-menu
1205 t
1206 (list ""
1207 (cons title
1208 (mapcar
1209 (function (lambda (i) (cons (car i) i)))
1210 alist))))
1211 ;; Immediately popup completion buffer:
1212 (prog1
1213 (let ((minibuffer-setup-hook 'minibuffer-completion-help))
1214 ;; BUG: this code assumes that "" is not a valid choice
1215 (completing-read
1216 (format "%s (default %s): " title (car (car alist)))
1217 alist nil t
1218 ;; (cons (car (car alist)) 0)
1219 nil
1220 ))
1221 ;; Redraw original screen:
1222 (sit-for 0)))))
1223 ;; Defaulting: convert "" to (car (car alist))
1224 (and (equal choice "") (setq choice (car (car alist))))
1225 (and (stringp choice) (setq choice (assoc choice alist)))
1226 (if choice (funcall cont choice) (message "No choice made!")))
1227 nil) ; return nothing
1228
1229 (defun ffap-menu-rescan nil
1230 "Search buffer for `ffap-menu-regexp' to build `ffap-menu-alist'.
1231 Applies `ffap-menu-text-plist' text properties at all matches."
1232 (interactive)
1233 (let ((ffap-next-regexp (or ffap-menu-regexp ffap-next-regexp))
1234 (range (- (point-max) (point-min))) item
1235 buffer-read-only ; to set text-properties
1236 ;; Avoid repeated searches of the *mode-alist:
1237 (major-mode (if (assq major-mode ffap-string-at-point-mode-alist)
1238 major-mode
1239 'file))
1240 )
1241 (setq ffap-menu-alist nil)
1242 (save-excursion
1243 (goto-char (point-min))
1244 (while (setq item (ffap-next-guess))
1245 (setq ffap-menu-alist (cons (cons item (point)) ffap-menu-alist))
1246 (add-text-properties (car ffap-string-at-point-region) (point)
1247 ffap-menu-text-plist)
1248 (message "Scanning...%2d%% <%s>"
1249 (/ (* 100 (- (point) (point-min))) range) item))))
1250 (message "Scanning...done")
1251 ;; Remove duplicates.
1252 (setq ffap-menu-alist ; sort by item
1253 (sort ffap-menu-alist
1254 (function
1255 (lambda (a b) (string-lessp (car a) (car b))))))
1256 (let ((ptr ffap-menu-alist))
1257 (while (cdr ptr)
1258 (if (equal (car (car ptr)) (car (car (cdr ptr))))
1259 (setcdr ptr (cdr (cdr ptr)))
1260 (setq ptr (cdr ptr)))))
1261 (setq ffap-menu-alist ; sort by position
1262 (sort ffap-menu-alist
1263 (function
1264 (lambda (a b) (< (cdr a) (cdr b)))))))
1265
1266 \f
1267 ;;; Mouse Support:
1268 ;;
1269 ;; See the suggested binding in ffap-bindings (near eof).
1270
1271 (defvar ffap-at-mouse-fallback 'ffap-menu
1272 "Invoked by `ffap-at-mouse' if no file or url at click.
1273 A command symbol, or nil for nothing.")
1274 (put 'ffap-at-mouse-fallback 'risky-local-variable t)
1275
1276 (defun ffap-at-mouse (e)
1277 "Find file or url guessed from text around mouse point.
1278 If none is found, call `ffap-at-mouse-fallback'."
1279 (interactive "e")
1280 (let ((guess
1281 ;; Maybe less surprising without the save-excursion?
1282 (save-excursion
1283 (mouse-set-point e)
1284 ;; Would like to do nothing unless click was *on* text. How?
1285 ;; (cdr (posn-col-row (event-start e))) is always same as
1286 ;; current column. For posn-x-y, need pixel-width!
1287 (ffap-guesser))))
1288 (cond
1289 (guess
1290 (ffap-highlight)
1291 (unwind-protect
1292 (progn
1293 (sit-for 0) ; display
1294 (message "Guessing `%s'" guess)
1295 (find-file-at-point guess))
1296 (ffap-highlight t)))
1297 ((and (interactive-p)
1298 ffap-at-mouse-fallback)
1299 (call-interactively ffap-at-mouse-fallback))
1300 ((message "No file or URL found at mouse click.")))))
1301
1302 \f
1303 ;;; ffap-other-* commands
1304 ;; Suggested by KPC.
1305
1306 (defun ffap-other-window nil
1307 "Like `ffap', but put buffer in another window."
1308 (interactive)
1309 (switch-to-buffer-other-window
1310 (save-window-excursion (call-interactively 'ffap) (current-buffer))))
1311
1312 (defun ffap-other-frame nil
1313 "Like `ffap', but put buffer in another frame."
1314 (interactive)
1315 (switch-to-buffer-other-frame
1316 (save-window-excursion (call-interactively 'ffap) (current-buffer))))
1317
1318 \f
1319 ;;; Bug Reporter:
1320
1321 (defun ffap-bug nil
1322 "Submit a bug report for the ffap package."
1323 ;; Important: keep the version string here in synch with that at top
1324 ;; of file! Could use lisp-mnt from Emacs 19, but that would depend
1325 ;; on being able to find the ffap.el source file.
1326 (interactive)
1327 (require 'reporter)
1328 (let ((reporter-prompt-for-summary-p t))
1329 (reporter-submit-bug-report
1330 "Michelangelo Grigni <mic@mathcs.emory.edu>"
1331 "ffap 1.6"
1332 (mapcar 'intern (all-completions "ffap-" obarray 'boundp)))))
1333
1334 (fset 'ffap-submit-bug 'ffap-bug) ; another likely name
1335
1336 \f
1337 ;;; Hooks for Gnus, VM, Rmail:
1338 ;;
1339 ;; If you do not like these bindings, write versions with whatever
1340 ;; bindings you would prefer.
1341
1342 (defun ffap-ro-mode-hook nil
1343 "Bind `ffap-next' and `ffap-menu' to M-l and M-m, resp."
1344 (local-set-key "\M-l" 'ffap-next)
1345 (local-set-key "\M-m" 'ffap-menu)
1346 )
1347
1348 (defun ffap-gnus-hook nil
1349 "Bind `ffap-gnus-next' and `ffap-gnus-menu' to M-l and M-m, resp."
1350 (set (make-local-variable 'ffap-foo-at-bar-prefix) "news") ; message-id's
1351 ;; Note "l", "L", "m", "M" are taken:
1352 (local-set-key "\M-l" 'ffap-gnus-next)
1353 (local-set-key "\M-m" 'ffap-gnus-menu))
1354
1355 (defun ffap-gnus-wrapper (form) ; used by both commands below
1356 (and (eq (current-buffer) (get-buffer gnus-summary-buffer))
1357 (gnus-summary-select-article)) ; get article of current line
1358 ;; Preserve selected buffer, but do not do save-window-excursion,
1359 ;; since we want to see any window created by the form. Temporarily
1360 ;; select the article buffer, so we can see any point movement.
1361 (let ((sb (window-buffer (selected-window))))
1362 (gnus-configure-windows 'article)
1363 (pop-to-buffer gnus-article-buffer)
1364 (widen)
1365 ;; Skip headers for ffap-gnus-next (which will wrap around)
1366 (if (eq (point) (point-min)) (search-forward "\n\n" nil t))
1367 (unwind-protect
1368 (eval form)
1369 (pop-to-buffer sb))))
1370
1371 (defun ffap-gnus-next nil
1372 "Run `ffap-next' in the gnus article buffer."
1373 (interactive) (ffap-gnus-wrapper '(ffap-next nil t)))
1374
1375 (defun ffap-gnus-menu nil
1376 "Run `ffap-menu' in the gnus article buffer."
1377 (interactive) (ffap-gnus-wrapper '(ffap-menu)))
1378
1379 \f
1380 ;;; ffap-bindings: offer default global bindings
1381
1382 (defvar ffap-bindings
1383 (nconc
1384 (cond
1385 ((not (eq window-system 'x))
1386 nil)
1387 ;; GNU coding standards say packages should not bind S-mouse-*.
1388 ;; Is it ok to simply suggest such a binding to the user?
1389 (ffap-xemacs
1390 '((global-set-key '(shift button3) 'ffap-at-mouse)))
1391 (t
1392 '((global-set-key [S-down-mouse-3] 'ffap-at-mouse))))
1393 '(
1394 (global-set-key "\C-x\C-f" 'find-file-at-point)
1395 (global-set-key "\C-x4f" 'ffap-other-window)
1396 (global-set-key "\C-x5f" 'ffap-other-frame)
1397 (add-hook 'gnus-summary-mode-hook 'ffap-gnus-hook)
1398 (add-hook 'gnus-article-mode-hook 'ffap-gnus-hook)
1399 (add-hook 'vm-mode-hook 'ffap-ro-mode-hook)
1400 (add-hook 'rmail-mode-hook 'ffap-ro-mode-hook)
1401 ;; (setq dired-x-hands-off-my-keys t) ; the default
1402 ))
1403 "List of forms evaluated by function `ffap-bindings'.
1404 A reasonable ffap installation needs just these two lines:
1405 (require 'ffap)
1406 (ffap-bindings)
1407 These are only suggestions, they may be modified or ignored.")
1408
1409 (defun ffap-bindings nil
1410 "Evaluate the forms in variable `ffap-bindings'."
1411 (eval (cons 'progn ffap-bindings)))
1412
1413 ;; Example modifications:
1414 ;;
1415 ;; (setq ffap-alist ; remove a feature in `ffap-alist'
1416 ;; (delete (assoc 'c-mode ffap-alist) ffap-alist))
1417 ;;
1418 ;; (setq ffap-alist ; add something to `ffap-alist'
1419 ;; (cons
1420 ;; (cons "^[Yy][Ss][Nn][0-9]+$"
1421 ;; (defun ffap-ysn (name)
1422 ;; (concat
1423 ;; "http://snorri.chem.washington.edu/ysnarchive/issuefiles/"
1424 ;; (substring name 3) ".html")))
1425 ;; ffap-alist))
1426
1427 \f
1428 ;;; XEmacs:
1429 ;; Extended suppport in another file, for copyright reasons.
1430 (or (not ffap-xemacs)
1431 (load "ffap-xe" t t)
1432 (message "ffap warning: ffap-xe.el not found"))
1433
1434 \f
1435 ;;; ffap.el ends here