(gnus-score-customize): Don't use `format' on `error' arguments.
[bpt/emacs.git] / lisp / ffap.el
1 ;;; ffap.el --- find file (or url) at point
2
3 ;; Copyright (C) 1995, 96, 97, 2000, 2004 Free Software Foundation, Inc.
4
5 ;; Author: Michelangelo Grigni <mic@mathcs.emory.edu>
6 ;; Maintainer: Rajesh Vaidheeswarran <rv@gnu.org>
7 ;; Created: 29 Mar 1993
8 ;; Keywords: files, hypermedia, matching, mouse, convenience
9 ;; X-URL: ftp://ftp.mathcs.emory.edu/pub/mic/emacs/
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 \f
29 ;;; Commentary:
30 ;;
31 ;; Command find-file-at-point replaces find-file. With a prefix, it
32 ;; behaves exactly like find-file. Without a prefix, it first tries
33 ;; to guess a default file or URL from the text around the point
34 ;; (`ffap-require-prefix' swaps these behaviors). This is useful for
35 ;; following references in situations such as mail or news buffers,
36 ;; README's, MANIFEST's, and so on. Submit bugs or suggestions with
37 ;; M-x ffap-bug.
38 ;;
39 ;; For the default installation, add this line to your .emacs file:
40 ;;
41 ;; (ffap-bindings) ; do default key bindings
42 ;;
43 ;; ffap-bindings makes the following global key bindings:
44 ;;
45 ;; C-x C-f find-file-at-point (abbreviated as ffap)
46 ;; C-x C-r ffap-read-only
47 ;; C-x C-v ffap-alternate-file
48 ;;
49 ;; C-x d dired-at-point
50 ;; C-x C-d ffap-list-directory
51 ;;
52 ;; C-x 4 f ffap-other-window
53 ;; C-x 4 r ffap-read-only-other-window
54 ;; C-x 4 d ffap-dired-other-window
55 ;;
56 ;; C-x 5 f ffap-other-frame
57 ;; C-x 5 r ffap-read-only-other-frame
58 ;; C-x 5 d ffap-dired-other-frame
59 ;;
60 ;; S-mouse-3 ffap-at-mouse
61 ;; C-S-mouse-3 ffap-menu
62 ;;
63 ;; ffap-bindings also adds hooks to make the following local bindings
64 ;; in vm, gnus, and rmail:
65 ;;
66 ;; M-l ffap-next, or ffap-gnus-next in gnus (l == "link")
67 ;; M-m ffap-menu, or ffap-gnus-menu in gnus (m == "menu")
68 ;;
69 ;; If you do not like these bindings, modify the variable
70 ;; `ffap-bindings', or write your own.
71 ;;
72 ;; If you use ange-ftp, browse-url, complete, efs, or w3, it is best
73 ;; to load or autoload them before ffap. If you use ff-paths, load it
74 ;; afterwards. Try apropos {C-h a ffap RET} to get a list of the many
75 ;; option variables. In particular, if ffap is slow, try these:
76 ;;
77 ;; (setq ffap-alist nil) ; faster, dumber prompting
78 ;; (setq ffap-machine-p-known 'accept) ; no pinging
79 ;; (setq ffap-url-regexp nil) ; disable URL features in ffap
80 ;; (setq ffap-shell-prompt-regexp nil) ; disable shell prompt stripping
81 ;;
82 ;; ffap uses `browse-url' (if found, else `w3-fetch') to fetch URL's.
83 ;; For a hairier `ffap-url-fetcher', try ffap-url.el (same ftp site).
84 ;; Also, you can add `ffap-menu-rescan' to various hooks to fontify
85 ;; the file and URL references within a buffer.
86
87 \f
88 ;;; Change Log:
89 ;;
90 ;; The History and Contributors moved to ffap.LOG (same ftp site),
91 ;; which also has some old examples and commentary from ffap 1.5.
92
93 \f
94 ;;; Todo list:
95 ;; * use kpsewhich
96 ;; * let "/dir/file#key" jump to key (tag or regexp) in /dir/file
97 ;; * find file of symbol if TAGS is loaded (like above)
98 ;; * break long menus into multiple panes (like imenu?)
99 ;; * notice node in "(dired)Virtual Dired" (quotes, parentheses, whitespace)
100 ;; * notice "machine.dom blah blah blah dir/file" (how?)
101 ;; * as w3 becomes standard, rewrite to rely more on its functions
102 ;; * regexp options for ffap-string-at-point, like font-lock (MCOOK)
103 ;; * v19: could replace `ffap-locate-file' with a quieter `locate-library'
104 ;; * handle "$(VAR)" in Makefiles
105 ;; * use the font-lock machinery
106
107 \f
108 ;;; Code:
109
110 (provide 'ffap)
111
112 ;; Please do not delete this variable, it is checked in bug reports.
113 (defconst ffap-version "1.9-fsf <97/06/25 13:21:41 mic>"
114 "The version of ffap: \"Major.Minor-Build <Timestamp>\"")
115
116
117 (defgroup ffap nil
118 "Find file or URL at point."
119 :link '(url-link :tag "URL" "ftp://ftp.mathcs.emory.edu/pub/mic/emacs/")
120 :group 'matching
121 :group 'convenience)
122
123 ;; The code is organized in pages, separated by formfeed characters.
124 ;; See the next two pages for standard customization ideas.
125
126 \f
127 ;;; User Variables:
128
129 (defun ffap-soft-value (name &optional default)
130 "Return value of symbol with NAME, if it is interned.
131 Otherwise return nil (or the optional DEFAULT value)."
132 ;; Bug: (ffap-soft-value "nil" 5) --> 5
133 (let ((sym (intern-soft name)))
134 (if (and sym (boundp sym)) (symbol-value sym) default)))
135
136 (defcustom ffap-shell-prompt-regexp
137 ;; This used to test for some shell prompts that don't have a space
138 ;; after them. The common root shell prompt (#) is not listed since it
139 ;; also doubles up as a valid URL character.
140 "[$%><]*"
141 "Paths matching this regexp are stripped off the shell prompt
142 If nil, ffap doesn't do shell prompt stripping."
143 :type '(choice (const :tag "Disable" nil)
144 (const :tag "Standard" "[$%><]*")
145 regexp)
146 :group 'ffap)
147
148 (defcustom ffap-ftp-regexp
149 ;; This used to test for ange-ftp or efs being present, but it should be
150 ;; harmless (and simpler) to give it this value unconditionally.
151 "\\`/[^/:]+:"
152 "*File names matching this regexp are treated as remote ffap.
153 If nil, ffap neither recognizes nor generates such names."
154 :type '(choice (const :tag "Disable" nil)
155 (const :tag "Standard" "\\`/[^/:]+:")
156 regexp)
157 :group 'ffap)
158
159 (defcustom ffap-url-unwrap-local t
160 "*If non-nil, convert `file:' URL to local file name before prompting."
161 :type 'boolean
162 :group 'ffap)
163
164 (defcustom ffap-url-unwrap-remote t
165 "*If non-nil, convert `ftp:' URL to remote file name before prompting.
166 This is ignored if `ffap-ftp-regexp' is nil."
167 :type 'boolean
168 :group 'ffap)
169
170 (defcustom ffap-ftp-default-user "anonymous"
171 "*User name in ftp file names generated by `ffap-host-to-path'.
172 Note this name may be omitted if it equals the default
173 \(either `efs-default-user' or `ange-ftp-default-user'\)."
174 :type 'string
175 :group 'ffap)
176
177 (defcustom ffap-rfs-regexp
178 ;; Remote file access built into file system? HP rfa or Andrew afs:
179 "\\`/\\(afs\\|net\\)/."
180 ;; afs only: (and (file-exists-p "/afs") "\\`/afs/.")
181 "*Matching file names are treated as remote. Use nil to disable."
182 :type 'regexp
183 :group 'ffap)
184
185 (defvar ffap-url-regexp
186 ;; Could just use `url-nonrelative-link' of w3, if loaded.
187 ;; This regexp is not exhaustive, it just matches common cases.
188 (concat
189 "\\`\\("
190 "news\\(post\\)?:\\|mailto:\\|file:" ; no host ok
191 "\\|"
192 "\\(ftp\\|https?\\|telnet\\|gopher\\|www\\|wais\\)://" ; needs host
193 "\\)." ; require one more character
194 )
195 "Regexp matching URL's. nil to disable URL features in ffap.")
196
197 (defcustom ffap-foo-at-bar-prefix "mailto"
198 "*Presumed URL prefix type of strings like \"<foo.9z@bar>\".
199 Sensible values are nil, \"news\", or \"mailto\"."
200 :type '(choice (const "mailto")
201 (const "news")
202 (const :tag "Disable" nil)
203 ;; string -- possible, but not really useful
204 )
205 :group 'ffap)
206
207 \f
208 ;;; Peanut Gallery (More User Variables):
209 ;;
210 ;; Users of ffap occasionally suggest new features. If I consider
211 ;; those features interesting but not clear winners (a matter of
212 ;; personal taste) I try to leave options to enable them. Read
213 ;; through this section for features that you like, put an appropriate
214 ;; enabler in your .emacs file.
215
216 (defcustom ffap-dired-wildcards "[*?][^/]*\\'"
217 "*A regexp matching filename wildcard characters, or nil.
218
219 If `find-file-at-point' gets a filename matching this pattern,
220 and `ffap-pass-wildcards-to-dired' is nil, it passes it on to
221 `find-file' with non-nil WILDCARDS argument, which expands
222 wildcards and visits multiple files. To visit a file whose name
223 contains wildcard characters you can suppress wildcard expansion
224 by setting `find-file-wildcards'. If `find-file-at-point' gets a
225 filename matching this pattern and `ffap-pass-wildcards-to-dired'
226 is non-nil, it passes it on to `dired'.
227
228 If `dired-at-point' gets a filename matching this pattern,
229 it passes it on to `dired'."
230 :type '(choice (const :tag "Disable" nil)
231 (const :tag "Enable" "[*?][^/]*\\'")
232 ;; regexp -- probably not useful
233 )
234 :group 'ffap)
235
236 (defcustom ffap-pass-wildcards-to-dired nil
237 "*If non-nil, pass filenames matching `ffap-dired-wildcards' to dired."
238 :type 'boolean
239 :group 'ffap)
240
241 (defcustom ffap-newfile-prompt nil
242 ;; Suggestion from RHOGEE, 11 Jul 1994. Disabled, I think this is
243 ;; better handled by `find-file-not-found-hooks'.
244 "*Whether `find-file-at-point' prompts about a nonexistent file."
245 :type 'boolean
246 :group 'ffap)
247
248 (defcustom ffap-require-prefix nil
249 ;; Suggestion from RHOGEE, 20 Oct 1994.
250 "*If set, reverses the prefix argument to `find-file-at-point'.
251 This is nil so neophytes notice ffap. Experts may prefer to disable
252 ffap most of the time."
253 :type 'boolean
254 :group 'ffap)
255
256 (defcustom ffap-file-finder 'find-file
257 "*The command called by `find-file-at-point' to find a file."
258 :type 'function
259 :group 'ffap)
260 (put 'ffap-file-finder 'risky-local-variable t)
261
262 (defcustom ffap-directory-finder 'dired
263 "*The command called by `dired-at-point' to find a directory."
264 :type 'function
265 :group 'ffap)
266 (put 'ffap-directory-finder 'risky-local-variable t)
267
268 (defcustom ffap-url-fetcher
269 (if (fboundp 'browse-url)
270 'browse-url ; rely on browse-url-browser-function
271 'w3-fetch)
272 ;; Remote control references:
273 ;; http://www.ncsa.uiuc.edu/SDG/Software/XMosaic/remote-control.html
274 ;; http://home.netscape.com/newsref/std/x-remote.html
275 "*A function of one argument, called by ffap to fetch an URL.
276 Reasonable choices are `w3-fetch' or a `browse-url-*' function.
277 For a fancy alternative, get `ffap-url.el'."
278 :type '(choice (const w3-fetch)
279 (const browse-url) ; in recent versions of browse-url
280 (const browse-url-netscape)
281 (const browse-url-mosaic)
282 function)
283 :group 'ffap)
284 (put 'ffap-url-fetcher 'risky-local-variable t)
285
286 \f
287 ;;; Compatibility:
288 ;;
289 ;; This version of ffap supports Emacs 20 only, see the ftp site
290 ;; for a more general version. The following functions are necessary
291 ;; "leftovers" from the more general version.
292
293 (defun ffap-mouse-event nil ; current mouse event, or nil
294 (and (listp last-nonmenu-event) last-nonmenu-event))
295 (defun ffap-event-buffer (event)
296 (window-buffer (car (event-start event))))
297
298 \f
299 ;;; Find Next Thing in buffer (`ffap-next'):
300 ;;
301 ;; Original ffap-next-url (URL's only) from RPECK 30 Mar 1995. Since
302 ;; then, broke it up into ffap-next-guess (noninteractive) and
303 ;; ffap-next (a command). It now work on files as well as url's.
304
305 (defcustom ffap-next-regexp
306 ;; If you want ffap-next to find URL's only, try this:
307 ;; (and ffap-url-regexp (string-match "\\\\`" ffap-url-regexp)
308 ;; (concat "\\<" (substring ffap-url-regexp 2))))
309 ;;
310 ;; It pays to put a big fancy regexp here, since ffap-guesser is
311 ;; much more time-consuming than regexp searching:
312 "[/:.~a-zA-Z]/\\|@[a-zA-Z][-a-zA-Z0-9]*\\."
313 "*Regular expression governing movements of `ffap-next'."
314 :type 'regexp
315 :group 'ffap)
316
317 (defvar ffap-next-guess nil
318 "Last value returned by `ffap-next-guess'.")
319
320 (defvar ffap-string-at-point-region '(1 1)
321 "List (BEG END), last region returned by `ffap-string-at-point'.")
322
323 (defun ffap-next-guess (&optional back lim)
324 "Move point to next file or URL, and return it as a string.
325 If nothing is found, leave point at limit and return nil.
326 Optional BACK argument makes search backwards.
327 Optional LIM argument limits the search.
328 Only considers strings that match `ffap-next-regexp'."
329 (or lim (setq lim (if back (point-min) (point-max))))
330 (let (guess)
331 (while (not (or guess (eq (point) lim)))
332 (funcall (if back 're-search-backward 're-search-forward)
333 ffap-next-regexp lim 'move)
334 (setq guess (ffap-guesser)))
335 ;; Go to end, so we do not get same guess twice:
336 (goto-char (nth (if back 0 1) ffap-string-at-point-region))
337 (setq ffap-next-guess guess)))
338
339 ;;;###autoload
340 (defun ffap-next (&optional back wrap)
341 "Search buffer for next file or URL, and run ffap.
342 Optional argument BACK says to search backwards.
343 Optional argument WRAP says to try wrapping around if necessary.
344 Interactively: use a single prefix to search backwards,
345 double prefix to wrap forward, triple to wrap backwards.
346 Actual search is done by `ffap-next-guess'."
347 (interactive
348 (cdr (assq (prefix-numeric-value current-prefix-arg)
349 '((1) (4 t) (16 nil t) (64 t t)))))
350 (let ((pt (point))
351 (guess (ffap-next-guess back)))
352 ;; Try wraparound if necessary:
353 (and (not guess) wrap
354 (goto-char (if back (point-max) (point-min)))
355 (setq guess (ffap-next-guess back pt)))
356 (if guess
357 (progn
358 (sit-for 0) ; display point movement
359 (find-file-at-point (ffap-prompter guess)))
360 (goto-char pt) ; restore point
361 (message "No %sfiles or URL's found"
362 (if wrap "" "more ")))))
363
364 (defun ffap-next-url (&optional back wrap)
365 "Like `ffap-next', but search with `ffap-url-regexp'."
366 (interactive)
367 (let ((ffap-next-regexp ffap-url-regexp))
368 (if (interactive-p)
369 (call-interactively 'ffap-next)
370 (ffap-next back wrap))))
371
372 \f
373 ;;; Machines (`ffap-machine-p'):
374
375 ;; I cannot decide a "best" strategy here, so these are variables. In
376 ;; particular, if `Pinging...' is broken or takes too long on your
377 ;; machine, try setting these all to accept or reject.
378 (defcustom ffap-machine-p-local 'reject ; this happens often
379 "*What `ffap-machine-p' does with hostnames that have no domain.
380 Value should be a symbol, one of `ping', `accept', and `reject'."
381 :type '(choice (const ping)
382 (const accept)
383 (const reject))
384 :group 'ffap)
385 (defcustom ffap-machine-p-known 'ping ; `accept' for higher speed
386 "*What `ffap-machine-p' does with hostnames that have a known domain.
387 Value should be a symbol, one of `ping', `accept', and `reject'.
388 See `mail-extr.el' for the known domains."
389 :type '(choice (const ping)
390 (const accept)
391 (const reject))
392 :group 'ffap)
393 (defcustom ffap-machine-p-unknown 'reject
394 "*What `ffap-machine-p' does with hostnames that have an unknown domain.
395 Value should be a symbol, one of `ping', `accept', and `reject'.
396 See `mail-extr.el' for the known domains."
397 :type '(choice (const ping)
398 (const accept)
399 (const reject))
400 :group 'ffap)
401
402 (defun ffap-what-domain (domain)
403 ;; Like what-domain in mail-extr.el, returns string or nil.
404 (require 'mail-extr)
405 (let ((ob (or (ffap-soft-value "mail-extr-all-top-level-domains")
406 (ffap-soft-value "all-top-level-domains")))) ; XEmacs
407 (and ob (get (intern-soft (downcase domain) ob) 'domain-name))))
408
409 (defun ffap-machine-p (host &optional service quiet strategy)
410 "Decide whether HOST is the name of a real, reachable machine.
411 Depending on the domain (none, known, or unknown), follow the strategy
412 named by the variable `ffap-machine-p-local', `ffap-machine-p-known',
413 or `ffap-machine-p-unknown'. Pinging uses `open-network-stream'.
414 Optional SERVICE specifies the port used \(default \"discard\"\).
415 Optional QUIET flag suppresses the \"Pinging...\" message.
416 Optional STRATEGY overrides the three variables above.
417 Returned values:
418 t means that HOST answered.
419 'accept means the relevant variable told us to accept.
420 \"mesg\" means HOST exists, but does not respond for some reason."
421 ;; Try some (Emory local):
422 ;; (ffap-machine-p "ftp" nil nil 'ping)
423 ;; (ffap-machine-p "nonesuch" nil nil 'ping)
424 ;; (ffap-machine-p "ftp.mathcs.emory.edu" nil nil 'ping)
425 ;; (ffap-machine-p "mathcs" 5678 nil 'ping)
426 ;; (ffap-machine-p "foo.bonk" nil nil 'ping)
427 ;; (ffap-machine-p "foo.bonk.com" nil nil 'ping)
428 (if (or (string-match "[^-a-zA-Z0-9.]" host) ; Illegal chars (?)
429 (not (string-match "[^0-9]" host))) ; 1: a number? 2: quick reject
430 nil
431 (let* ((domain
432 (and (string-match "\\.[^.]*$" host)
433 (downcase (substring host (1+ (match-beginning 0))))))
434 (what-domain (if domain (ffap-what-domain domain) "Local")))
435 (or strategy
436 (setq strategy
437 (cond ((not domain) ffap-machine-p-local)
438 ((not what-domain) ffap-machine-p-unknown)
439 (t ffap-machine-p-known))))
440 (cond
441 ((eq strategy 'accept) 'accept)
442 ((eq strategy 'reject) nil)
443 ((not (fboundp 'open-network-stream)) nil)
444 ;; assume (eq strategy 'ping)
445 (t
446 (or quiet
447 (if (stringp what-domain)
448 (message "Pinging %s (%s)..." host what-domain)
449 (message "Pinging %s ..." host)))
450 (condition-case error
451 (progn
452 (delete-process
453 (open-network-stream
454 "ffap-machine-p" nil host (or service "discard")))
455 t)
456 (error
457 (let ((mesg (car (cdr error))))
458 (cond
459 ;; v18:
460 ((string-match "^Unknown host" mesg) nil)
461 ((string-match "not responding$" mesg) mesg)
462 ;; v19:
463 ;; (file-error "connection failed" "permission denied"
464 ;; "nonesuch" "ffap-machine-p")
465 ;; (file-error "connection failed" "host is unreachable"
466 ;; "gopher.house.gov" "ffap-machine-p")
467 ;; (file-error "connection failed" "address already in use"
468 ;; "ftp.uu.net" "ffap-machine-p")
469 ((equal mesg "connection failed")
470 (if (equal (nth 2 error) "permission denied")
471 nil ; host does not exist
472 ;; Other errors mean the host exists:
473 (nth 2 error)))
474 ;; Could be "Unknown service":
475 (t (signal (car error) (cdr error))))))))))))
476
477 \f
478 ;;; Possibly Remote Resources:
479
480 (defun ffap-replace-file-component (fullname name)
481 "In remote FULLNAME, replace path with NAME. May return nil."
482 ;; Use ange-ftp or efs if loaded, but do not load them otherwise.
483 (let (found)
484 (mapcar
485 (function (lambda (sym) (and (fboundp sym) (setq found sym))))
486 '(
487 efs-replace-path-component
488 ange-ftp-replace-path-component
489 ange-ftp-replace-name-component
490 ))
491 (and found
492 (fset 'ffap-replace-file-component found)
493 (funcall found fullname name))))
494 ;; (ffap-replace-file-component "/who@foo.com:/whatever" "/new")
495
496 (defun ffap-file-suffix (file)
497 "Return trailing `.foo' suffix of FILE, or nil if none."
498 (let ((pos (string-match "\\.[^./]*\\'" file)))
499 (and pos (substring file pos nil))))
500
501 (defvar ffap-compression-suffixes '(".gz" ".Z") ; .z is mostly dead
502 "List of suffixes tried by `ffap-file-exists-string'.")
503
504 (defun ffap-file-exists-string (file &optional nomodify)
505 ;; Early jka-compr versions modified file-exists-p to return the
506 ;; filename, maybe modified by adding a suffix like ".gz". That
507 ;; broke the interface of file-exists-p, so it was later dropped.
508 ;; Here we document and simulate the old behavior.
509 "Return FILE (maybe modified) if the file exists, else nil.
510 When using jka-compr (a.k.a. `auto-compression-mode'), the returned
511 name may have a suffix added from `ffap-compression-suffixes'.
512 The optional NOMODIFY argument suppresses the extra search."
513 (cond
514 ((not file) nil) ; quietly reject nil
515 ((file-exists-p file) file) ; try unmodified first
516 ;; three reasons to suppress search:
517 (nomodify nil)
518 ((not (rassq 'jka-compr-handler file-name-handler-alist)) nil)
519 ((member (ffap-file-suffix file) ffap-compression-suffixes) nil)
520 (t ; ok, do the search
521 (let ((list ffap-compression-suffixes) try ret)
522 (while list
523 (if (file-exists-p (setq try (concat file (car list))))
524 (setq ret try list nil)
525 (setq list (cdr list))))
526 ret))))
527
528 (defun ffap-file-remote-p (filename)
529 "If FILENAME looks remote, return it (maybe slightly improved)."
530 ;; (ffap-file-remote-p "/user@foo.bar.com:/pub")
531 ;; (ffap-file-remote-p "/cssun.mathcs.emory.edu://dir")
532 ;; (ffap-file-remote-p "/ffap.el:80")
533 (or (and ffap-ftp-regexp
534 (string-match ffap-ftp-regexp filename)
535 ;; Convert "/host.com://dir" to "/host:/dir", to handle a dieing
536 ;; practice of advertising ftp files as "host.dom://filename".
537 (if (string-match "//" filename)
538 ;; (replace-match "/" nil nil filename)
539 (concat (substring filename 0 (1+ (match-beginning 0)))
540 (substring filename (match-end 0)))
541 filename))
542 (and ffap-rfs-regexp
543 (string-match ffap-rfs-regexp filename)
544 filename)))
545
546 (defun ffap-machine-at-point nil
547 "Return machine name at point if it exists, or nil."
548 (let ((mach (ffap-string-at-point 'machine)))
549 (and (ffap-machine-p mach) mach)))
550
551 (defsubst ffap-host-to-filename (host)
552 "Convert HOST to something like \"/USER@HOST:\" or \"/HOST:\".
553 Looks at `ffap-ftp-default-user', returns \"\" for \"localhost\"."
554 (if (equal host "localhost")
555 ""
556 (let ((user ffap-ftp-default-user))
557 ;; Avoid including the user if it is same as default:
558 (if (or (equal user (ffap-soft-value "ange-ftp-default-user"))
559 (equal user (ffap-soft-value "efs-default-user")))
560 (setq user nil))
561 (concat "/" user (and user "@") host ":"))))
562
563 (defun ffap-fixup-machine (mach)
564 ;; Convert a hostname into an url, an ftp file name, or nil.
565 (cond
566 ((not (and ffap-url-regexp (stringp mach))) nil)
567 ;; gopher.well.com
568 ((string-match "\\`gopher[-.]" mach) ; or "info"?
569 (concat "gopher://" mach "/"))
570 ;; www.ncsa.uiuc.edu
571 ((and (string-match "\\`w\\(ww\\|eb\\)[-.]" mach))
572 (concat "http://" mach "/"))
573 ;; More cases? Maybe "telnet:" for archie?
574 (ffap-ftp-regexp (ffap-host-to-filename mach))
575 ))
576
577 (defvar ffap-newsgroup-regexp "^[a-z]+\\.[-+a-z_0-9.]+$"
578 "Strings not matching this fail `ffap-newsgroup-p'.")
579 (defvar ffap-newsgroup-heads ; entirely inadequate
580 '("alt" "comp" "gnu" "misc" "news" "sci" "soc" "talk")
581 "Used by `ffap-newsgroup-p' if gnus is not running.")
582
583 (defun ffap-newsgroup-p (string)
584 "Return STRING if it looks like a newsgroup name, else nil."
585 (and
586 (string-match ffap-newsgroup-regexp string)
587 (let ((htbs '(gnus-active-hashtb gnus-newsrc-hashtb gnus-killed-hashtb))
588 (heads ffap-newsgroup-heads)
589 htb ret)
590 (while htbs
591 (setq htb (car htbs) htbs (cdr htbs))
592 (condition-case nil
593 (progn
594 ;; errs: htb symbol may be unbound, or not a hash-table.
595 ;; gnus-gethash is just a macro for intern-soft.
596 (and (symbol-value htb)
597 (intern-soft string (symbol-value htb))
598 (setq ret string htbs nil))
599 ;; If we made it this far, gnus is running, so ignore "heads":
600 (setq heads nil))
601 (error nil)))
602 (or ret (not heads)
603 (let ((head (string-match "\\`\\([a-z]+\\)\\." string)))
604 (and head (setq head (substring string 0 (match-end 1)))
605 (member head heads)
606 (setq ret string))))
607 ;; Is there ever a need to modify string as a newsgroup name?
608 ret)))
609
610 (defsubst ffap-url-p (string)
611 "If STRING looks like an url, return it (maybe improved), else nil."
612 (let ((case-fold-search t))
613 (and ffap-url-regexp (string-match ffap-url-regexp string)
614 ;; I lied, no improvement:
615 string)))
616
617 ;; Broke these out of ffap-fixup-url, for use of ffap-url package.
618 (defsubst ffap-url-unwrap-local (url)
619 "Return URL as a local file, or nil. Ignores `ffap-url-regexp'."
620 (and (string-match "\\`\\(file\\|ftp\\):/?\\([^/]\\|\\'\\)" url)
621 (substring url (1+ (match-end 1)))))
622 (defsubst ffap-url-unwrap-remote (url)
623 "Return URL as a remote file, or nil. Ignores `ffap-url-regexp'."
624 (and (string-match "\\`\\(ftp\\|file\\)://\\([^:/]+\\):?\\(/.*\\)" url)
625 (concat
626 (ffap-host-to-filename (substring url (match-beginning 2) (match-end 2)))
627 (substring url (match-beginning 3) (match-end 3)))))
628 ;; Test: (ffap-url-unwrap-remote "ftp://foo.com/bar.boz")
629
630 (defun ffap-fixup-url (url)
631 "Clean up URL and return it, maybe as a file name."
632 (cond
633 ((not (stringp url)) nil)
634 ((and ffap-url-unwrap-local (ffap-url-unwrap-local url)))
635 ((and ffap-url-unwrap-remote ffap-ftp-regexp
636 (ffap-url-unwrap-remote url)))
637 ((fboundp 'url-normalize-url) ; may autoload url (part of w3)
638 (url-normalize-url url))
639 (url)))
640
641 \f
642 ;;; File Name Handling:
643 ;;
644 ;; The upcoming ffap-alist actions need various utilities to prepare
645 ;; and search directories. Too many features here.
646
647 ;; (defun ffap-last (l) (while (cdr l) (setq l (cdr l))) l)
648 ;; (defun ffap-splice (func inlist)
649 ;; "Equivalent to (apply 'nconc (mapcar FUNC INLIST)), but less consing."
650 ;; (let* ((head (cons 17 nil)) (last head))
651 ;; (while inlist
652 ;; (setcdr last (funcall func (car inlist)))
653 ;; (setq last (ffap-last last) inlist (cdr inlist)))
654 ;; (cdr head)))
655
656 (defun ffap-list-env (env &optional empty)
657 "Return a list of strings parsed from environment variable ENV.
658 Optional EMPTY is the default list if \(getenv ENV\) is undefined, and
659 also is substituted for the first empty-string component, if there is one.
660 Uses `path-separator' to separate the path into substrings."
661 ;; We cannot use parse-colon-path (files.el), since it kills
662 ;; "//" entries using file-name-as-directory.
663 ;; Similar: dired-split, TeX-split-string, and RHOGEE's psg-list-env
664 ;; in ff-paths and bib-cite. The EMPTY arg may help mimic kpathsea.
665 (if (or empty (getenv env)) ; should return something
666 (let ((start 0) match dir ret)
667 (setq env (concat (getenv env) path-separator))
668 (while (setq match (string-match path-separator env start))
669 (setq dir (substring env start match) start (1+ match))
670 ;;(and (file-directory-p dir) (not (member dir ret)) ...)
671 (setq ret (cons dir ret)))
672 (setq ret (nreverse ret))
673 (and empty (setq match (member "" ret))
674 (progn ; allow string or list here
675 (setcdr match (append (cdr-safe empty) (cdr match)))
676 (setcar match (or (car-safe empty) empty))))
677 ret)))
678
679 (defun ffap-reduce-path (path)
680 "Remove duplicates and non-directories from PATH list."
681 (let (ret tem)
682 (while path
683 (setq tem path path (cdr path))
684 (if (equal (car tem) ".") (setcar tem ""))
685 (or (member (car tem) ret)
686 (not (file-directory-p (car tem)))
687 (progn (setcdr tem ret) (setq ret tem))))
688 (nreverse ret)))
689
690 (defun ffap-all-subdirs (dir &optional depth)
691 "Return list all subdirectories under DIR, starting with itself.
692 Directories beginning with \".\" are ignored, and directory symlinks
693 are listed but never searched (to avoid loops).
694 Optional DEPTH limits search depth."
695 (and (file-exists-p dir)
696 (ffap-all-subdirs-loop (expand-file-name dir) (or depth -1))))
697
698 (defun ffap-all-subdirs-loop (dir depth) ; internal
699 (setq depth (1- depth))
700 (cons dir
701 (and (not (eq depth -1))
702 (apply 'nconc
703 (mapcar
704 (function
705 (lambda (d)
706 (cond
707 ((not (file-directory-p d)) nil)
708 ((file-symlink-p d) (list d))
709 (t (ffap-all-subdirs-loop d depth)))))
710 (directory-files dir t "\\`[^.]")
711 )))))
712
713 (defvar ffap-kpathsea-depth 1
714 "Bound on depth of subdirectory search in `ffap-kpathsea-expand-path'.
715 Set to 0 to avoid all searching, or nil for no limit.")
716
717 (defun ffap-kpathsea-expand-path (path)
718 "Replace each \"//\"-suffixed dir in PATH by a list of its subdirs.
719 The subdirs begin with the original directory, and the depth of the
720 search is bounded by `ffap-kpathsea-depth'. This is intended to mimic
721 kpathsea, a library used by some versions of TeX."
722 (apply 'nconc
723 (mapcar
724 (function
725 (lambda (dir)
726 (if (string-match "[^/]//\\'" dir)
727 (ffap-all-subdirs (substring dir 0 -2) ffap-kpathsea-depth)
728 (list dir))))
729 path)))
730
731 (defun ffap-locate-file (file &optional nosuffix path dir-ok)
732 ;; The Emacs 20 version of locate-library could almost replace this,
733 ;; except it does not let us override the suffix list. The
734 ;; compression-suffixes search moved to ffap-file-exists-string.
735 "A generic path-searching function, mimics `load' by default.
736 Returns path to file that \(load FILE\) would load, or nil.
737 Optional NOSUFFIX, if nil or t, is like the fourth argument
738 for load: whether to try the suffixes (\".elc\" \".el\" \"\").
739 If a nonempty list, it is a list of suffixes to try instead.
740 Optional PATH is a list of directories instead of `load-path'.
741 Optional DIR-OK means that returning a directory is allowed,
742 DIR-OK is already implicit if FILE looks like a directory.
743
744 This uses ffap-file-exists-string, which may try adding suffixes from
745 `ffap-compression-suffixes'."
746 (or path (setq path load-path))
747 (or dir-ok (setq dir-ok (equal "" (file-name-nondirectory file))))
748 (if (file-name-absolute-p file)
749 (setq path (list (file-name-directory file))
750 file (file-name-nondirectory file)))
751 (let ((suffixes-to-try
752 (cond
753 ((consp nosuffix) nosuffix)
754 (nosuffix '(""))
755 (t '(".elc" ".el" ""))))
756 suffixes try found)
757 (while path
758 (setq suffixes suffixes-to-try)
759 (while suffixes
760 (setq try (ffap-file-exists-string
761 (expand-file-name
762 (concat file (car suffixes)) (car path))))
763 (if (and try (or dir-ok (not (file-directory-p try))))
764 (setq found try suffixes nil path nil)
765 (setq suffixes (cdr suffixes))))
766 (setq path (cdr path)))
767 found))
768
769 \f
770 ;;; Action List (`ffap-alist'):
771 ;;
772 ;; These search actions depend on the major-mode or regexps matching
773 ;; the current name. The little functions and their variables are
774 ;; deferred to the next section, at some loss of "code locality". A
775 ;; good example of featuritis. Trim this list for speed.
776
777 (defvar ffap-alist
778 '(
779 ("" . ffap-completable) ; completion, slow on some systems
780 ("\\.info\\'" . ffap-info) ; gzip.info
781 ("\\`info/" . ffap-info-2) ; info/emacs
782 ("\\`[-a-z]+\\'" . ffap-info-3) ; (emacs)Top [only in the parentheses]
783 ("\\.elc?\\'" . ffap-el) ; simple.el, simple.elc
784 (emacs-lisp-mode . ffap-el-mode) ; rmail, gnus, simple, custom
785 ;; (lisp-interaction-mode . ffap-el-mode) ; maybe
786 (finder-mode . ffap-el-mode) ; type {C-h p} and try it
787 (help-mode . ffap-el-mode) ; maybe useful
788 (c++-mode . ffap-c-mode) ; search ffap-c-path
789 (cc-mode . ffap-c-mode) ; same
790 ("\\.\\([chCH]\\|cc\\|hh\\)\\'" . ffap-c-mode) ; stdio.h
791 (fortran-mode . ffap-fortran-mode) ; FORTRAN requested by MDB
792 ("\\.[fF]\\'" . ffap-fortran-mode)
793 (tex-mode . ffap-tex-mode) ; search ffap-tex-path
794 (latex-mode . ffap-latex-mode) ; similar
795 ("\\.\\(tex\\|sty\\|doc\\|cls\\)\\'" . ffap-tex)
796 ("\\.bib\\'" . ffap-bib) ; search ffap-bib-path
797 ("\\`\\." . ffap-home) ; .emacs, .bashrc, .profile
798 ("\\`~/" . ffap-lcd) ; |~/misc/ffap.el.Z|
799 ("^[Rr][Ff][Cc][- #]?\\([0-9]+\\)" ; no $
800 . ffap-rfc) ; "100% RFC2100 compliant"
801 (dired-mode . ffap-dired) ; maybe in a subdirectory
802 )
803 "Alist of \(KEY . FUNCTION\) pairs parsed by `ffap-file-at-point'.
804 If string NAME at point (maybe \"\") is not a file or url, these pairs
805 specify actions to try creating such a string. A pair matches if either
806 KEY is a symbol, and it equals `major-mode', or
807 KEY is a string, it should matches NAME as a regexp.
808 On a match, \(FUNCTION NAME\) is called and should return a file, an
809 url, or nil. If nil, search the alist for further matches.")
810
811 (put 'ffap-alist 'risky-local-variable t)
812
813 ;; Example `ffap-alist' modifications:
814 ;;
815 ;; (setq ffap-alist ; remove a feature in `ffap-alist'
816 ;; (delete (assoc 'c-mode ffap-alist) ffap-alist))
817 ;;
818 ;; (setq ffap-alist ; add something to `ffap-alist'
819 ;; (cons
820 ;; (cons "^YSN[0-9]+$"
821 ;; (defun ffap-ysn (name)
822 ;; (concat
823 ;; "http://www.physics.uiuc.edu/"
824 ;; "ysn/httpd/htdocs/ysnarchive/issuefiles/"
825 ;; (substring name 3) ".html")))
826 ;; ffap-alist))
827
828 \f
829 ;;; Action Definitions:
830 ;;
831 ;; Define various default members of `ffap-alist'.
832
833 (defun ffap-completable (name)
834 (let* ((dir (or (file-name-directory name) default-directory))
835 (cmp (file-name-completion (file-name-nondirectory name) dir)))
836 (and cmp (concat dir cmp))))
837
838 (defun ffap-home (name) (ffap-locate-file name t '("~")))
839
840 (defun ffap-info (name)
841 (ffap-locate-file
842 name '("" ".info")
843 (or (ffap-soft-value "Info-directory-list")
844 (ffap-soft-value "Info-default-directory-list")
845 )))
846
847 (defun ffap-info-2 (name) (ffap-info (substring name 5)))
848
849 (defun ffap-info-3 (name)
850 ;; This ignores the node! "(emacs)Top" same as "(emacs)Intro"
851 (and (equal (ffap-string-around) "()") (ffap-info name)))
852
853 (defun ffap-el (name) (ffap-locate-file name t))
854
855 (defun ffap-el-mode (name)
856 ;; If name == "foo.el" we will skip it, since ffap-el already
857 ;; searched for it once. (This assumes the default ffap-alist.)
858 (and (not (string-match "\\.el\\'" name))
859 (ffap-locate-file name '(".el"))))
860
861 (defvar ffap-c-path
862 ;; Need smarter defaults here! Suggestions welcome.
863 '("/usr/include" "/usr/local/include"))
864 (defun ffap-c-mode (name)
865 (ffap-locate-file name t ffap-c-path))
866
867 (defvar ffap-fortran-path '("../include" "/usr/include"))
868
869 (defun ffap-fortran-mode (name)
870 (ffap-locate-file name t ffap-fortran-path))
871
872 (defvar ffap-tex-path
873 t ; delayed initialization
874 "Path where `ffap-tex-mode' looks for tex files.
875 If t, `ffap-tex-init' will initialize this when needed.")
876
877 (defun ffap-tex-init nil
878 ;; Compute ffap-tex-path if it is now t.
879 (and (eq t ffap-tex-path)
880 ;; this may be slow, so say something
881 (message "Initializing ffap-tex-path ...")
882 (setq ffap-tex-path
883 (ffap-reduce-path
884 (cons
885 "."
886 (ffap-kpathsea-expand-path
887 (append
888 (ffap-list-env "TEXINPUTS")
889 ;; (ffap-list-env "BIBINPUTS")
890 (ffap-soft-value
891 "TeX-macro-global" ; AUCTeX
892 '("/usr/local/lib/tex/macros"
893 "/usr/local/lib/tex/inputs")))))))))
894
895 (defun ffap-tex-mode (name)
896 (ffap-tex-init)
897 (ffap-locate-file name '(".tex" "") ffap-tex-path))
898
899 (defun ffap-latex-mode (name)
900 (ffap-tex-init)
901 ;; only rare need for ""
902 (ffap-locate-file name '(".cls" ".sty" ".tex" "") ffap-tex-path))
903
904 (defun ffap-tex (name)
905 (ffap-tex-init)
906 (ffap-locate-file name t ffap-tex-path))
907
908 (defvar ffap-bib-path
909 (ffap-list-env "BIBINPUTS"
910 (ffap-reduce-path
911 '(
912 ;; a few wild guesses, need better
913 "/usr/local/lib/tex/macros/bib" ; Solaris?
914 "/usr/lib/texmf/bibtex/bib" ; Linux?
915 ))))
916
917 (defun ffap-bib (name)
918 (ffap-locate-file name t ffap-bib-path))
919
920 (defun ffap-dired (name)
921 (let ((pt (point)) dir try)
922 (save-excursion
923 (and (progn
924 (beginning-of-line)
925 (looking-at " *[-d]r[-w][-x][-r][-w][-x][-r][-w][-x] "))
926 (re-search-backward "^ *$" nil t)
927 (re-search-forward "^ *\\([^ \t\n:]*\\):\n *total " pt t)
928 (file-exists-p
929 (setq try
930 (expand-file-name
931 name
932 (buffer-substring
933 (match-beginning 1) (match-end 1)))))
934 try))))
935
936 ;; Maybe a "Lisp Code Directory" reference:
937 (defun ffap-lcd (name)
938 (and
939 (or
940 ;; lisp-dir-apropos output buffer:
941 (string-match "Lisp Code Dir" (buffer-name))
942 ;; Inside an LCD entry like |~/misc/ffap.el.Z|,
943 ;; or maybe the holy LCD-Datafile itself:
944 (member (ffap-string-around) '("||" "|\n")))
945 (concat
946 ;; lispdir.el may not be loaded yet:
947 (ffap-host-to-filename
948 (ffap-soft-value "elisp-archive-host"
949 "archive.cis.ohio-state.edu"))
950 (file-name-as-directory
951 (ffap-soft-value "elisp-archive-directory"
952 "/pub/gnu/emacs/elisp-archive/"))
953 (substring name 2))))
954
955 (defvar ffap-rfc-path
956 (concat (ffap-host-to-filename "ds.internic.net") "/rfc/rfc%s.txt"))
957
958 (defun ffap-rfc (name)
959 (format ffap-rfc-path
960 (substring name (match-beginning 1) (match-end 1))))
961
962 \f
963 ;;; At-Point Functions:
964
965 (defvar ffap-string-at-point-mode-alist
966 '(
967 ;; The default, used when the `major-mode' is not found.
968 ;; Slightly controversial decisions:
969 ;; * strip trailing "@" and ":"
970 ;; * no commas (good for latex)
971 (file "--:$+<>@-Z_a-z~*?" "<@" "@>;.,!:")
972 ;; An url, or maybe a email/news message-id:
973 (url "--:=&?$+@-Z_a-z~#,%;*" "^A-Za-z0-9" ":;.,!?")
974 ;; Find a string that does *not* contain a colon:
975 (nocolon "--9$+<>@-Z_a-z~" "<@" "@>;.,!?")
976 ;; A machine:
977 (machine "-a-zA-Z0-9." "" ".")
978 ;; Mathematica paths: allow backquotes
979 (math-mode ",-:$+<>@-Z_a-z~`" "<" "@>;.,!?`:")
980 )
981 "Alist of \(MODE CHARS BEG END\), where MODE is a symbol,
982 possibly a major-mode name, or one of the symbol
983 `file', `url', `machine', and `nocolon'.
984 `ffap-string-at-point' uses the data fields as follows:
985 1. find a maximal string of CHARS around point,
986 2. strip BEG chars before point from the beginning,
987 3. Strip END chars after point from the end.")
988
989 (defvar ffap-string-at-point nil
990 ;; Added at suggestion of RHOGEE (for ff-paths), 7/24/95.
991 "Last string returned by `ffap-string-at-point'.")
992
993 (defun ffap-string-at-point (&optional mode)
994 "Return a string of characters from around point.
995 MODE (defaults to value of `major-mode') is a symbol used to look up string
996 syntax parameters in `ffap-string-at-point-mode-alist'.
997 If MODE is not found, we use `file' instead of MODE.
998 If the region is active, return a string from the region.
999 Sets `ffap-string-at-point' and `ffap-string-at-point-region'."
1000 (let* ((args
1001 (cdr
1002 (or (assq (or mode major-mode) ffap-string-at-point-mode-alist)
1003 (assq 'file ffap-string-at-point-mode-alist))))
1004 (pt (point))
1005 (str
1006 (if (and transient-mark-mode mark-active)
1007 (buffer-substring
1008 (setcar ffap-string-at-point-region (region-beginning))
1009 (setcar (cdr ffap-string-at-point-region) (region-end)))
1010 (buffer-substring
1011 (save-excursion
1012 (skip-chars-backward (car args))
1013 (skip-chars-forward (nth 1 args) pt)
1014 (setcar ffap-string-at-point-region (point)))
1015 (save-excursion
1016 (skip-chars-forward (car args))
1017 (skip-chars-backward (nth 2 args) pt)
1018 (setcar (cdr ffap-string-at-point-region) (point)))))))
1019 (set-text-properties 0 (length str) nil str)
1020 (setq ffap-string-at-point str)))
1021
1022 (defun ffap-string-around nil
1023 ;; Sometimes useful to decide how to treat a string.
1024 "Return string of two chars around last `ffap-string-at-point'.
1025 Assumes the buffer has not changed."
1026 (save-excursion
1027 (format "%c%c"
1028 (progn
1029 (goto-char (car ffap-string-at-point-region))
1030 (preceding-char)) ; maybe 0
1031 (progn
1032 (goto-char (nth 1 ffap-string-at-point-region))
1033 (following-char)) ; maybe 0
1034 )))
1035
1036 (defun ffap-copy-string-as-kill (&optional mode)
1037 ;; Requested by MCOOK. Useful?
1038 "Call `ffap-string-at-point', and copy result to `kill-ring'."
1039 (interactive)
1040 (let ((str (ffap-string-at-point mode)))
1041 (if (equal "" str)
1042 (message "No string found around point.")
1043 (kill-new str)
1044 ;; Older: (apply 'copy-region-as-kill ffap-string-at-point-region)
1045 (message "Copied to kill ring: %s" str))))
1046
1047 (defun ffap-url-at-point nil
1048 "Return url from around point if it exists, or nil."
1049 ;; Could use w3's url-get-url-at-point instead. Both handle "URL:",
1050 ;; ignore non-relative links, trim punctuation. The other will
1051 ;; actually look back if point is in whitespace, but I would rather
1052 ;; ffap be less aggressive in such situations.
1053 (and
1054 ffap-url-regexp
1055 (or
1056 ;; In a w3 buffer button?
1057 (and (eq major-mode 'w3-mode)
1058 ;; interface recommended by wmperry:
1059 (w3-view-this-url t))
1060 ;; Is there a reason not to strip trailing colon?
1061 (let ((name (ffap-string-at-point 'url)))
1062 (cond
1063 ((string-match "^url:" name) (setq name (substring name 4)))
1064 ((and (string-match "\\`[^:</>@]+@[^:</>@]+[a-zA-Z0-9]\\'" name)
1065 ;; "foo@bar": could be "mailto" or "news" (a Message-ID).
1066 ;; Without "<>" it must be "mailto". Otherwise could be
1067 ;; either, so consult `ffap-foo-at-bar-prefix'.
1068 (let ((prefix (if (and (equal (ffap-string-around) "<>")
1069 ;; Expect some odd characters:
1070 (string-match "[$.0-9].*[$.0-9].*@" name))
1071 ;; Could be news:
1072 ffap-foo-at-bar-prefix
1073 "mailto")))
1074 (and prefix (setq name (concat prefix ":" name))))))
1075 ((ffap-newsgroup-p name) (setq name (concat "news:" name)))
1076 ((and (string-match "\\`[a-z0-9]+\\'" name) ; <mic> <root> <nobody>
1077 (equal (ffap-string-around) "<>")
1078 ;; (ffap-user-p name):
1079 (not (string-match "~" (expand-file-name (concat "~" name))))
1080 )
1081 (setq name (concat "mailto:" name)))
1082 )
1083 (and (ffap-url-p name) name)
1084 ))))
1085
1086 (defvar ffap-gopher-regexp
1087 "^.*\\<\\(Type\\|Name\\|Path\\|Host\\|Port\\) *= *\\(.*\\) *$"
1088 "Regexp Matching a line in a gopher bookmark (maybe indented).
1089 The two subexpressions are the KEY and VALUE.")
1090
1091 (defun ffap-gopher-at-point nil
1092 "If point is inside a gopher bookmark block, return its url."
1093 ;; `gopher-parse-bookmark' from gopher.el is not so robust
1094 (save-excursion
1095 (beginning-of-line)
1096 (if (looking-at ffap-gopher-regexp)
1097 (progn
1098 (while (and (looking-at ffap-gopher-regexp) (not (bobp)))
1099 (forward-line -1))
1100 (or (looking-at ffap-gopher-regexp) (forward-line 1))
1101 (let ((type "1") name path host (port "70"))
1102 (while (looking-at ffap-gopher-regexp)
1103 (let ((var (intern
1104 (downcase
1105 (buffer-substring (match-beginning 1)
1106 (match-end 1)))))
1107 (val (buffer-substring (match-beginning 2)
1108 (match-end 2))))
1109 (set var val)
1110 (forward-line 1)))
1111 (if (and path (string-match "^ftp:.*@" path))
1112 (concat "ftp://"
1113 (substring path 4 (1- (match-end 0)))
1114 (substring path (match-end 0)))
1115 (and (= (length type) 1)
1116 host;; (ffap-machine-p host)
1117 (concat "gopher://" host
1118 (if (equal port "70") "" (concat ":" port))
1119 "/" type path))))))))
1120
1121 (defvar ffap-ftp-sans-slash-regexp
1122 (and
1123 ffap-ftp-regexp
1124 ;; Note: by now, we know it is not an url.
1125 ;; Icky regexp avoids: default: 123: foo::bar cs:pub
1126 ;; It does match on: mic@cs: cs:/pub mathcs.emory.edu: (point at end)
1127 "\\`\\([^:@]+@[^:@]+:\\|[^@.:]+\\.[^@:]+:\\|[^:]+:[~/]\\)\\([^:]\\|\\'\\)")
1128 "Strings matching this are coerced to ftp file names by ffap.
1129 That is, ffap just prepends \"/\". Set to nil to disable.")
1130
1131 (defun ffap-file-at-point nil
1132 "Return filename from around point if it exists, or nil.
1133 Existence test is skipped for names that look remote.
1134 If the filename is not obvious, it also tries `ffap-alist',
1135 which may actually result in an url rather than a filename."
1136 ;; Note: this function does not need to look for url's, just
1137 ;; filenames. On the other hand, it is responsible for converting
1138 ;; a pseudo-url "site.com://dir" to an ftp file name
1139 (let* ((case-fold-search t) ; url prefixes are case-insensitive
1140 (data (match-data))
1141 (string (ffap-string-at-point)) ; uses mode alist
1142 (name
1143 (or (condition-case nil
1144 (and (not (string-match "//" string)) ; foo.com://bar
1145 (substitute-in-file-name string))
1146 (error nil))
1147 string))
1148 (abs (file-name-absolute-p name))
1149 (default-directory default-directory))
1150 (unwind-protect
1151 (cond
1152 ;; Immediate rejects (/ and // and /* are too common in C/C++):
1153 ((member name '("" "/" "//" "/*" ".")) nil)
1154 ;; Immediately test local filenames. If default-directory is
1155 ;; remote, you probably already have a connection.
1156 ((and (not abs) (ffap-file-exists-string name)))
1157 ;; Try stripping off line numbers; good for compilation/grep output.
1158 ((and (not abs) (string-match ":[0-9]" name)
1159 (ffap-file-exists-string (substring name 0 (match-beginning 0)))))
1160 ;; Try stripping off prominent (non-root - #) shell prompts
1161 ;; if the ffap-shell-prompt-regexp is non-nil.
1162 ((and ffap-shell-prompt-regexp
1163 (not abs) (string-match ffap-shell-prompt-regexp name)
1164 (ffap-file-exists-string (substring name (match-end 0)))))
1165 ;; Accept remote names without actual checking (too slow):
1166 ((if abs
1167 (ffap-file-remote-p name)
1168 ;; Try adding a leading "/" (common omission in ftp file names):
1169 (and
1170 ffap-ftp-sans-slash-regexp
1171 (string-match ffap-ftp-sans-slash-regexp name)
1172 (ffap-file-remote-p (concat "/" name)))))
1173 ;; Ok, not remote, try the existence test even if it is absolute:
1174 ((and abs (ffap-file-exists-string name)))
1175 ;; If it contains a colon, get rid of it (and return if exists)
1176 ((and (string-match path-separator name)
1177 (setq name (ffap-string-at-point 'nocolon))
1178 (ffap-file-exists-string name)))
1179 ;; File does not exist, try the alist:
1180 ((let ((alist ffap-alist) tem try case-fold-search)
1181 (while (and alist (not try))
1182 (setq tem (car alist) alist (cdr alist))
1183 (if (or (eq major-mode (car tem))
1184 (and (stringp (car tem))
1185 (string-match (car tem) name)))
1186 (and (setq try
1187 (condition-case nil
1188 (funcall (cdr tem) name)
1189 (error nil)))
1190 (setq try (or
1191 (ffap-url-p try) ; not a file!
1192 (ffap-file-remote-p try)
1193 (ffap-file-exists-string try))))))
1194 try))
1195 ;; Alist failed? Try to guess an active remote connection
1196 ;; from buffer variables, and try once more, both as an
1197 ;; absolute and relative file name on that remote host.
1198 ((let* (ffap-rfs-regexp ; suppress
1199 (remote-dir
1200 (cond
1201 ((ffap-file-remote-p default-directory))
1202 ((and (eq major-mode 'internal-ange-ftp-mode)
1203 (string-match "^\\*ftp \\(.*\\)@\\(.*\\)\\*$"
1204 (buffer-name)))
1205 (concat "/" (substring (buffer-name) 5 -1) ":"))
1206 ;; This is too often a bad idea:
1207 ;;((and (eq major-mode 'w3-mode)
1208 ;; (stringp url-current-server))
1209 ;; (host-to-ange-path url-current-server))
1210 )))
1211 (and remote-dir
1212 (or
1213 (and (string-match "\\`\\(/?~?ftp\\)/" name)
1214 (ffap-file-exists-string
1215 (ffap-replace-file-component
1216 remote-dir (substring name (match-end 1)))))
1217 (ffap-file-exists-string
1218 (ffap-replace-file-component remote-dir name))))))
1219 ((and ffap-dired-wildcards
1220 (string-match ffap-dired-wildcards name)
1221 abs
1222 (ffap-file-exists-string (file-name-directory
1223 (directory-file-name name)))
1224 name))
1225 ;; Try all parent directories by deleting the trailing directory
1226 ;; name until existing directory is found or name stops changing
1227 ((let ((dir name))
1228 (while (and dir
1229 (not (ffap-file-exists-string dir))
1230 (not (equal dir (setq dir (file-name-directory
1231 (directory-file-name dir)))))))
1232 (ffap-file-exists-string dir)))
1233 )
1234 (set-match-data data))))
1235 \f
1236 ;;; Prompting (`ffap-read-file-or-url'):
1237 ;;
1238 ;; We want to complete filenames as in read-file-name, but also url's
1239 ;; which read-file-name-internal would truncate at the "//" string.
1240 ;; The solution here is to replace read-file-name-internal with
1241 ;; `ffap-read-file-or-url-internal', which checks the minibuffer
1242 ;; contents before attempting to complete filenames.
1243
1244 (defun ffap-read-file-or-url (prompt guess)
1245 "Read file or url from minibuffer, with PROMPT and initial GUESS."
1246 (or guess (setq guess default-directory))
1247 (let (dir)
1248 ;; Tricky: guess may have or be a local directory, like "w3/w3.elc"
1249 ;; or "w3/" or "../el/ffap.el" or "../../../"
1250 (or (ffap-url-p guess)
1251 (progn
1252 (or (ffap-file-remote-p guess)
1253 (setq guess
1254 (abbreviate-file-name (expand-file-name guess))
1255 ))
1256 (setq dir (file-name-directory guess))))
1257 (let ((minibuffer-completing-file-name t))
1258 (setq guess
1259 (completing-read
1260 prompt
1261 'ffap-read-file-or-url-internal
1262 dir
1263 nil
1264 (if dir (cons guess (length dir)) guess)
1265 (list 'file-name-history)
1266 (and buffer-file-name
1267 (abbreviate-file-name buffer-file-name)))))
1268 ;; Do file substitution like (interactive "F"), suggested by MCOOK.
1269 (or (ffap-url-p guess) (setq guess (substitute-in-file-name guess)))
1270 ;; Should not do it on url's, where $ is a common (VMS?) character.
1271 ;; Note: upcoming url.el package ought to handle this automatically.
1272 guess))
1273
1274 (defun ffap-read-url-internal (string dir action)
1275 "Complete url's from history, treating given string as valid."
1276 (let ((hist (ffap-soft-value "url-global-history-hash-table")))
1277 (cond
1278 ((not action)
1279 (or (try-completion string hist) string))
1280 ((eq action t)
1281 (or (all-completions string hist) (list string)))
1282 ;; action == lambda, documented where? Tests whether string is a
1283 ;; valid "match". Let us always say yes.
1284 (t t))))
1285
1286 (defun ffap-read-file-or-url-internal (string dir action)
1287 (unless dir
1288 (setq dir default-directory))
1289 (unless string
1290 (setq string default-directory))
1291 (if (ffap-url-p string)
1292 (ffap-read-url-internal string dir action)
1293 (read-file-name-internal string dir action)))
1294
1295 ;; The rest of this page is just to work with package complete.el.
1296 ;; This code assumes that you load ffap.el after complete.el.
1297 ;;
1298 ;; We must inform complete about whether our completion function
1299 ;; will do filename style completion.
1300
1301 (defun ffap-complete-as-file-p nil
1302 ;; Will `minibuffer-completion-table' complete the minibuffer
1303 ;; contents as a filename? Assumes the minibuffer is current.
1304 ;; Note: t and non-nil mean somewhat different reasons.
1305 (if (eq minibuffer-completion-table 'ffap-read-file-or-url-internal)
1306 (not (ffap-url-p (buffer-string))) ; t
1307 (and minibuffer-completing-file-name '(t)))) ;list
1308
1309 (and
1310 (featurep 'complete)
1311 (if (boundp 'PC-completion-as-file-name-predicate)
1312 ;; modern version of complete.el, just set the variable:
1313 (setq PC-completion-as-file-name-predicate 'ffap-complete-as-file-p)))
1314
1315 \f
1316 ;;; Highlighting (`ffap-highlight'):
1317 ;;
1318 ;; Based on overlay highlighting in Emacs 19.28 isearch.el.
1319
1320 (defvar ffap-highlight t
1321 "If non-nil, ffap highlights the current buffer substring.")
1322
1323 (defvar ffap-highlight-overlay nil
1324 "Overlay used by `ffap-highlight'.")
1325
1326 (defun ffap-highlight (&optional remove)
1327 "If `ffap-highlight' is set, highlight the guess in this buffer.
1328 That is, the last buffer substring found by `ffap-string-at-point'.
1329 Optional argument REMOVE means to remove any such highlighting.
1330 Uses the face `ffap' if it is defined, or else `highlight'."
1331 (cond
1332 (remove
1333 (and ffap-highlight-overlay
1334 (delete-overlay ffap-highlight-overlay))
1335 )
1336 ((not ffap-highlight) nil)
1337 (ffap-highlight-overlay
1338 (move-overlay
1339 ffap-highlight-overlay
1340 (car ffap-string-at-point-region)
1341 (nth 1 ffap-string-at-point-region)
1342 (current-buffer)))
1343 (t
1344 (setq ffap-highlight-overlay
1345 (apply 'make-overlay ffap-string-at-point-region))
1346 (overlay-put ffap-highlight-overlay 'face
1347 (if (facep 'ffap) 'ffap 'highlight)))))
1348
1349 \f
1350 ;;; Main Entrance (`find-file-at-point' == `ffap'):
1351
1352 (defun ffap-guesser nil
1353 "Return file or URL or nil, guessed from text around point."
1354 (or (and ffap-url-regexp
1355 (ffap-fixup-url (or (ffap-url-at-point)
1356 (ffap-gopher-at-point))))
1357 (ffap-file-at-point) ; may yield url!
1358 (ffap-fixup-machine (ffap-machine-at-point))))
1359
1360 (defun ffap-prompter (&optional guess)
1361 ;; Does guess and prompt step for find-file-at-point.
1362 ;; Extra complication for the temporary highlighting.
1363 (unwind-protect
1364 ;; This catch will let ffap-alist entries do their own prompting
1365 ;; and then maybe skip over this prompt (ff-paths, for example).
1366 (catch 'ffap-prompter
1367 (ffap-read-file-or-url
1368 (if ffap-url-regexp "Find file or URL: " "Find file: ")
1369 (prog1
1370 (setq guess (or guess (ffap-guesser))) ; using ffap-alist here
1371 (and guess (ffap-highlight))
1372 )))
1373 (ffap-highlight t)))
1374
1375 ;;;###autoload
1376 (defun find-file-at-point (&optional filename)
1377 "Find FILENAME, guessing a default from text around point.
1378 If `ffap-url-regexp' is not nil, the FILENAME may also be an URL.
1379 With a prefix, this command behaves exactly like `ffap-file-finder'.
1380 If `ffap-require-prefix' is set, the prefix meaning is reversed.
1381 See also the variables `ffap-dired-wildcards', `ffap-newfile-prompt',
1382 and the functions `ffap-file-at-point' and `ffap-url-at-point'.
1383
1384 See <ftp://ftp.mathcs.emory.edu/pub/mic/emacs/> for latest version."
1385 (interactive)
1386 (if (and (interactive-p)
1387 (if ffap-require-prefix (not current-prefix-arg)
1388 current-prefix-arg))
1389 ;; Do exactly the ffap-file-finder command, even the prompting:
1390 (let (current-prefix-arg) ; we already interpreted it
1391 (call-interactively ffap-file-finder))
1392 (or filename (setq filename (ffap-prompter)))
1393 (cond
1394 ((ffap-url-p filename)
1395 (let (current-prefix-arg) ; w3 2.3.25 bug, reported by KPC
1396 (funcall ffap-url-fetcher filename)))
1397 ((and ffap-pass-wildcards-to-dired
1398 ffap-dired-wildcards
1399 (string-match ffap-dired-wildcards filename))
1400 (funcall ffap-directory-finder filename))
1401 ((and ffap-dired-wildcards
1402 (string-match ffap-dired-wildcards filename)
1403 find-file-wildcards
1404 ;; Check if it's find-file that supports wildcards arg
1405 (memq ffap-file-finder '(find-file find-alternate-file)))
1406 (funcall ffap-file-finder (expand-file-name filename) t))
1407 ((or (not ffap-newfile-prompt)
1408 (file-exists-p filename)
1409 (y-or-n-p "File does not exist, create buffer? "))
1410 (funcall ffap-file-finder
1411 ;; expand-file-name fixes "~/~/.emacs" bug sent by CHUCKR.
1412 (expand-file-name filename)))
1413 ;; User does not want to find a non-existent file:
1414 ((signal 'file-error (list "Opening file buffer"
1415 "no such file or directory"
1416 filename))))))
1417
1418 ;; Shortcut: allow {M-x ffap} rather than {M-x find-file-at-point}.
1419 ;;;###autoload
1420 (defalias 'ffap 'find-file-at-point)
1421
1422 \f
1423 ;;; Menu support (`ffap-menu'):
1424
1425 (defvar ffap-menu-regexp nil
1426 "*If non-nil, overrides `ffap-next-regexp' during `ffap-menu'.
1427 Make this more restrictive for faster menu building.
1428 For example, try \":/\" for URL (and some ftp) references.")
1429
1430 (defvar ffap-menu-alist nil
1431 "Buffer local cache of menu presented by `ffap-menu'.")
1432 (make-variable-buffer-local 'ffap-menu-alist)
1433
1434 (defvar ffap-menu-text-plist
1435 (cond
1436 ((display-mouse-p) '(face bold mouse-face highlight)) ; keymap <mousy-map>
1437 (t nil))
1438 "Text properties applied to strings found by `ffap-menu-rescan'.
1439 These properties may be used to fontify the menu references.")
1440
1441 ;;;###autoload
1442 (defun ffap-menu (&optional rescan)
1443 "Put up a menu of files and urls mentioned in this buffer.
1444 Then set mark, jump to choice, and try to fetch it. The menu is
1445 cached in `ffap-menu-alist', and rebuilt by `ffap-menu-rescan'.
1446 The optional RESCAN argument \(a prefix, interactively\) forces
1447 a rebuild. Searches with `ffap-menu-regexp'."
1448 (interactive "P")
1449 ;; (require 'imenu) -- no longer used, but roughly emulated
1450 (if (or (not ffap-menu-alist) rescan
1451 ;; or if the first entry is wrong:
1452 (and ffap-menu-alist
1453 (let ((first (car ffap-menu-alist)))
1454 (save-excursion
1455 (goto-char (cdr first))
1456 (not (equal (car first) (ffap-guesser)))))))
1457 (ffap-menu-rescan))
1458 ;; Tail recursive:
1459 (ffap-menu-ask
1460 (if ffap-url-regexp "Find file or URL" "Find file")
1461 (cons (cons "*Rescan Buffer*" -1) ffap-menu-alist)
1462 'ffap-menu-cont))
1463
1464 (defun ffap-menu-cont (choice) ; continuation of ffap-menu
1465 (if (< (cdr choice) 0)
1466 (ffap-menu t) ; *Rescan*
1467 (push-mark)
1468 (goto-char (cdr choice))
1469 ;; Momentary highlight:
1470 (unwind-protect
1471 (progn
1472 (and ffap-highlight (ffap-guesser) (ffap-highlight))
1473 (sit-for 0) ; display
1474 (find-file-at-point (car choice)))
1475 (ffap-highlight t))))
1476
1477 (defun ffap-menu-ask (title alist cont)
1478 "Prompt from a menu of choices, and then apply some action.
1479 Arguments are TITLE, ALIST, and CONT \(a continuation function\).
1480 This uses either a menu or the minibuffer depending on invocation.
1481 The TITLE string is used as either the prompt or menu title.
1482 Each ALIST entry looks like (STRING . DATA) and defines one choice.
1483 Function CONT is applied to the entry chosen by the user."
1484 ;; Note: this function is used with a different continuation
1485 ;; by the ffap-url add-on package.
1486 ;; Could try rewriting to use easymenu.el or lmenu.el.
1487 (let (choice)
1488 (cond
1489 ;; Emacs mouse:
1490 ((and (fboundp 'x-popup-menu) (ffap-mouse-event))
1491 (setq choice
1492 (x-popup-menu
1493 t
1494 (list "" (cons title
1495 (mapcar (function (lambda (i) (cons (car i) i)))
1496 alist))))))
1497 ;; minibuffer with completion buffer:
1498 (t
1499 (let ((minibuffer-setup-hook 'minibuffer-completion-help))
1500 ;; Bug: prompting may assume unique strings, no "".
1501 (setq choice
1502 (completing-read
1503 (format "%s (default %s): " title (car (car alist)))
1504 alist nil t
1505 ;; (cons (car (car alist)) 0)
1506 nil)))
1507 (sit-for 0) ; redraw original screen
1508 ;; Convert string to its entry, or else the default:
1509 (setq choice (or (assoc choice alist) (car alist))))
1510 )
1511 (if choice
1512 (funcall cont choice)
1513 (message "No choice made!") ; possible with menus
1514 nil)))
1515
1516 (defun ffap-menu-rescan nil
1517 "Search buffer for `ffap-menu-regexp' to build `ffap-menu-alist'.
1518 Applies `ffap-menu-text-plist' text properties at all matches."
1519 (interactive)
1520 (let ((ffap-next-regexp (or ffap-menu-regexp ffap-next-regexp))
1521 (range (- (point-max) (point-min)))
1522 (mod (buffer-modified-p)) ; was buffer modified?
1523 buffer-read-only ; to set text-properties
1524 item
1525 ;; Avoid repeated searches of the *mode-alist:
1526 (major-mode (if (assq major-mode ffap-string-at-point-mode-alist)
1527 major-mode
1528 'file)))
1529 (setq ffap-menu-alist nil)
1530 (unwind-protect
1531 (save-excursion
1532 (goto-char (point-min))
1533 (while (setq item (ffap-next-guess))
1534 (setq ffap-menu-alist (cons (cons item (point)) ffap-menu-alist))
1535 (add-text-properties (car ffap-string-at-point-region) (point)
1536 ffap-menu-text-plist)
1537 (message "Scanning...%2d%% <%s>"
1538 (/ (* 100 (- (point) (point-min))) range) item)))
1539 (or mod (set-buffer-modified-p nil))))
1540 (message "Scanning...done")
1541 ;; Remove duplicates.
1542 (setq ffap-menu-alist ; sort by item
1543 (sort ffap-menu-alist
1544 (function
1545 (lambda (a b) (string-lessp (car a) (car b))))))
1546 (let ((ptr ffap-menu-alist)) ; remove duplicates
1547 (while (cdr ptr)
1548 (if (equal (car (car ptr)) (car (car (cdr ptr))))
1549 (setcdr ptr (cdr (cdr ptr)))
1550 (setq ptr (cdr ptr)))))
1551 (setq ffap-menu-alist ; sort by position
1552 (sort ffap-menu-alist
1553 (function
1554 (lambda (a b) (< (cdr a) (cdr b)))))))
1555
1556 \f
1557 ;;; Mouse Support (`ffap-at-mouse'):
1558 ;;
1559 ;; See the suggested binding in ffap-bindings (near eof).
1560
1561 (defvar ffap-at-mouse-fallback nil ; ffap-menu? too time-consuming
1562 "Command invoked by `ffap-at-mouse' if nothing found at click, or nil.
1563 Ignored when `ffap-at-mouse' is called programmatically.")
1564 (put 'ffap-at-mouse-fallback 'risky-local-variable t)
1565
1566 ;;;###autoload
1567 (defun ffap-at-mouse (e)
1568 "Find file or url guessed from text around mouse click.
1569 Interactively, calls `ffap-at-mouse-fallback' if no guess is found.
1570 Return value:
1571 * if a guess string is found, return it (after finding it)
1572 * if the fallback is called, return whatever it returns
1573 * otherwise, nil"
1574 (interactive "e")
1575 (let ((guess
1576 ;; Maybe less surprising without the save-excursion?
1577 (save-excursion
1578 (mouse-set-point e)
1579 ;; Would prefer to do nothing unless click was *on* text. How
1580 ;; to tell that the click was beyond the end of current line?
1581 (ffap-guesser))))
1582 (cond
1583 (guess
1584 (set-buffer (ffap-event-buffer e))
1585 (ffap-highlight)
1586 (unwind-protect
1587 (progn
1588 (sit-for 0) ; display
1589 (message "Finding `%s'" guess)
1590 (find-file-at-point guess)
1591 guess) ; success: return non-nil
1592 (ffap-highlight t)))
1593 ((interactive-p)
1594 (if ffap-at-mouse-fallback
1595 (call-interactively ffap-at-mouse-fallback)
1596 (message "No file or url found at mouse click.")
1597 nil)) ; no fallback, return nil
1598 ;; failure: return nil
1599 )))
1600
1601 \f
1602 ;;; ffap-other-*, ffap-read-only-*, ffap-alternate-* commands:
1603
1604 ;; There could be a real `ffap-noselect' function, but we would need
1605 ;; at least two new user variables, and there is no w3-fetch-noselect.
1606 ;; So instead, we just fake it with a slow save-window-excursion.
1607
1608 (defun ffap-other-window nil
1609 "Like `ffap', but put buffer in another window.
1610 Only intended for interactive use."
1611 (interactive)
1612 (let (value)
1613 (switch-to-buffer-other-window
1614 (save-window-excursion
1615 (setq value (call-interactively 'ffap))
1616 (unless (or (bufferp value) (bufferp (car-safe value)))
1617 (setq value (current-buffer)))
1618 (current-buffer)))
1619 value))
1620
1621 (defun ffap-other-frame nil
1622 "Like `ffap', but put buffer in another frame.
1623 Only intended for interactive use."
1624 (interactive)
1625 ;; Extra code works around dedicated windows (noted by JENS, 7/96):
1626 (let* ((win (selected-window))
1627 (wdp (window-dedicated-p win))
1628 value)
1629 (unwind-protect
1630 (progn
1631 (set-window-dedicated-p win nil)
1632 (switch-to-buffer-other-frame
1633 (save-window-excursion
1634 (setq value (call-interactively 'ffap))
1635 (unless (or (bufferp value) (bufferp (car-safe value)))
1636 (setq value (current-buffer)))
1637 (current-buffer))))
1638 (set-window-dedicated-p win wdp))
1639 value))
1640
1641 (defun ffap-read-only ()
1642 "Like `ffap', but mark buffer as read-only.
1643 Only intended for interactive use."
1644 (interactive)
1645 (let ((value (call-interactively 'ffap)))
1646 (unless (or (bufferp value) (bufferp (car-safe value)))
1647 (setq value (current-buffer)))
1648 (mapc (lambda (b) (with-current-buffer b (toggle-read-only 1)))
1649 (if (listp value) value (list value)))
1650 value))
1651
1652 (defun ffap-read-only-other-window ()
1653 "Like `ffap', but put buffer in another window and mark as read-only.
1654 Only intended for interactive use."
1655 (interactive)
1656 (let ((value (ffap-other-window)))
1657 (mapc (lambda (b) (with-current-buffer b (toggle-read-only 1)))
1658 (if (listp value) value (list value)))
1659 value))
1660
1661 (defun ffap-read-only-other-frame ()
1662 "Like `ffap', but put buffer in another frame and mark as read-only.
1663 Only intended for interactive use."
1664 (interactive)
1665 (let ((value (ffap-other-frame)))
1666 (mapc (lambda (b) (with-current-buffer b (toggle-read-only 1)))
1667 (if (listp value) value (list value)))
1668 value))
1669
1670 (defun ffap-alternate-file ()
1671 "Like `ffap' and `find-alternate-file'.
1672 Only intended for interactive use."
1673 (interactive)
1674 (let ((ffap-file-finder 'find-alternate-file))
1675 (call-interactively 'ffap)))
1676
1677 \f
1678 ;;; Bug Reporter:
1679
1680 (defun ffap-bug nil
1681 "Submit a bug report for the ffap package."
1682 ;; Important: keep the version string here in synch with that at top
1683 ;; of file! Could use lisp-mnt from Emacs 19, but that would depend
1684 ;; on being able to find the ffap.el source file.
1685 (interactive)
1686 (require 'reporter)
1687 (let ((reporter-prompt-for-summary-p t))
1688 (reporter-submit-bug-report
1689 "Michelangelo Grigni <mic@mathcs.emory.edu>"
1690 "ffap"
1691 (mapcar 'intern (all-completions "ffap-" obarray 'boundp)))))
1692
1693 (fset 'ffap-submit-bug 'ffap-bug) ; another likely name
1694
1695 \f
1696 ;;; Hooks for Gnus, VM, Rmail:
1697 ;;
1698 ;; If you do not like these bindings, write versions with whatever
1699 ;; bindings you would prefer.
1700
1701 (defun ffap-ro-mode-hook nil
1702 "Bind `ffap-next' and `ffap-menu' to M-l and M-m, resp."
1703 (local-set-key "\M-l" 'ffap-next)
1704 (local-set-key "\M-m" 'ffap-menu)
1705 )
1706
1707 (defun ffap-gnus-hook nil
1708 "Bind `ffap-gnus-next' and `ffap-gnus-menu' to M-l and M-m, resp."
1709 (set (make-local-variable 'ffap-foo-at-bar-prefix) "news") ; message-id's
1710 ;; Note "l", "L", "m", "M" are taken:
1711 (local-set-key "\M-l" 'ffap-gnus-next)
1712 (local-set-key "\M-m" 'ffap-gnus-menu))
1713
1714 (defun ffap-gnus-wrapper (form) ; used by both commands below
1715 (and (eq (current-buffer) (get-buffer gnus-summary-buffer))
1716 (gnus-summary-select-article)) ; get article of current line
1717 ;; Preserve selected buffer, but do not do save-window-excursion,
1718 ;; since we want to see any window created by the form. Temporarily
1719 ;; select the article buffer, so we can see any point movement.
1720 (let ((sb (window-buffer (selected-window))))
1721 (gnus-configure-windows 'article)
1722 (pop-to-buffer gnus-article-buffer)
1723 (widen)
1724 ;; Skip headers for ffap-gnus-next (which will wrap around)
1725 (if (eq (point) (point-min)) (search-forward "\n\n" nil t))
1726 (unwind-protect
1727 (eval form)
1728 (pop-to-buffer sb))))
1729
1730 (defun ffap-gnus-next nil
1731 "Run `ffap-next' in the gnus article buffer."
1732 (interactive) (ffap-gnus-wrapper '(ffap-next nil t)))
1733
1734 (defun ffap-gnus-menu nil
1735 "Run `ffap-menu' in the gnus article buffer."
1736 (interactive) (ffap-gnus-wrapper '(ffap-menu)))
1737
1738 \f
1739 (defcustom dired-at-point-require-prefix nil
1740 "*If set, reverses the prefix argument to `dired-at-point'.
1741 This is nil so neophytes notice ffap. Experts may prefer to disable
1742 ffap most of the time."
1743 :type 'boolean
1744 :group 'ffap
1745 :version "20.3")
1746
1747 ;;;###autoload
1748 (defun dired-at-point (&optional filename)
1749 "Start Dired, defaulting to file at point. See `ffap'."
1750 (interactive)
1751 (if (and (interactive-p)
1752 (if dired-at-point-require-prefix
1753 (not current-prefix-arg)
1754 current-prefix-arg))
1755 (let (current-prefix-arg) ; already interpreted
1756 (call-interactively ffap-directory-finder))
1757 (or filename (setq filename (dired-at-point-prompter)))
1758 (cond
1759 ((ffap-url-p filename)
1760 (funcall ffap-url-fetcher filename))
1761 ((and ffap-dired-wildcards
1762 (string-match ffap-dired-wildcards filename))
1763 (funcall ffap-directory-finder filename))
1764 ((file-exists-p filename)
1765 (if (file-directory-p filename)
1766 (funcall ffap-directory-finder
1767 (expand-file-name filename))
1768 (funcall ffap-directory-finder
1769 (concat (expand-file-name filename) "*"))))
1770 ((and (file-writable-p
1771 (or (file-name-directory (directory-file-name filename))
1772 filename))
1773 (y-or-n-p "Directory does not exist, create it? "))
1774 (make-directory filename)
1775 (funcall ffap-directory-finder filename))
1776 ((error "No such file or directory `%s'" filename)))))
1777
1778 (defun dired-at-point-prompter (&optional guess)
1779 ;; Does guess and prompt step for find-file-at-point.
1780 ;; Extra complication for the temporary highlighting.
1781 (unwind-protect
1782 (ffap-read-file-or-url
1783 (if ffap-url-regexp "Dired file or URL: " "Dired file: ")
1784 (prog1
1785 (setq guess (or guess
1786 (let ((guess (ffap-guesser)))
1787 (if (or (not guess)
1788 (ffap-url-p guess)
1789 (ffap-file-remote-p guess))
1790 guess
1791 (setq guess (abbreviate-file-name
1792 (expand-file-name guess)))
1793 (cond
1794 ;; Interpret local directory as a directory.
1795 ((file-directory-p guess)
1796 (file-name-as-directory guess))
1797 ;; Get directory component from local files.
1798 ((file-regular-p guess)
1799 (file-name-directory guess))
1800 (guess))))
1801 ))
1802 (and guess (ffap-highlight))))
1803 (ffap-highlight t)))
1804 \f
1805 ;;; ffap-dired-other-*, ffap-list-directory commands:
1806
1807 (defun ffap-dired-other-window ()
1808 "Like `dired-at-point', but put buffer in another window.
1809 Only intended for interactive use."
1810 (interactive)
1811 (let (value)
1812 (switch-to-buffer-other-window
1813 (save-window-excursion
1814 (setq value (call-interactively 'dired-at-point))
1815 (current-buffer)))
1816 value))
1817
1818 (defun ffap-dired-other-frame ()
1819 "Like `dired-at-point', but put buffer in another frame.
1820 Only intended for interactive use."
1821 (interactive)
1822 ;; Extra code works around dedicated windows (noted by JENS, 7/96):
1823 (let* ((win (selected-window))
1824 (wdp (window-dedicated-p win))
1825 value)
1826 (unwind-protect
1827 (progn
1828 (set-window-dedicated-p win nil)
1829 (switch-to-buffer-other-frame
1830 (save-window-excursion
1831 (setq value (call-interactively 'dired-at-point))
1832 (current-buffer))))
1833 (set-window-dedicated-p win wdp))
1834 value))
1835
1836 (defun ffap-list-directory ()
1837 "Like `dired-at-point' and `list-directory'.
1838 Only intended for interactive use."
1839 (interactive)
1840 (let ((ffap-directory-finder 'list-directory))
1841 (call-interactively 'dired-at-point)))
1842
1843 \f
1844 ;;; Offer default global bindings (`ffap-bindings'):
1845
1846 (defvar ffap-bindings
1847 '(
1848 (global-set-key [S-mouse-3] 'ffap-at-mouse)
1849 (global-set-key [C-S-mouse-3] 'ffap-menu)
1850
1851 (global-set-key "\C-x\C-f" 'find-file-at-point)
1852 (global-set-key "\C-x\C-r" 'ffap-read-only)
1853 (global-set-key "\C-x\C-v" 'ffap-alternate-file)
1854
1855 (global-set-key "\C-x4f" 'ffap-other-window)
1856 (global-set-key "\C-x5f" 'ffap-other-frame)
1857 (global-set-key "\C-x4r" 'ffap-read-only-other-window)
1858 (global-set-key "\C-x5r" 'ffap-read-only-other-frame)
1859
1860 (global-set-key "\C-xd" 'dired-at-point)
1861 (global-set-key "\C-x4d" 'ffap-dired-other-window)
1862 (global-set-key "\C-x5d" 'ffap-dired-other-frame)
1863 (global-set-key "\C-x\C-d" 'ffap-list-directory)
1864
1865 (add-hook 'gnus-summary-mode-hook 'ffap-gnus-hook)
1866 (add-hook 'gnus-article-mode-hook 'ffap-gnus-hook)
1867 (add-hook 'vm-mode-hook 'ffap-ro-mode-hook)
1868 (add-hook 'rmail-mode-hook 'ffap-ro-mode-hook)
1869 ;; (setq dired-x-hands-off-my-keys t) ; the default
1870 )
1871 "List of binding forms evaluated by function `ffap-bindings'.
1872 A reasonable ffap installation needs just this one line:
1873 (ffap-bindings)
1874 Of course if you do not like these bindings, just roll your own!")
1875
1876 ;;;###autoload
1877 (defun ffap-bindings nil
1878 "Evaluate the forms in variable `ffap-bindings'."
1879 (interactive)
1880 (eval (cons 'progn ffap-bindings)))
1881
1882 \f
1883
1884 ;;; arch-tag: 9dd3e88a-5dec-4607-bd57-60ae9ede8ebc
1885 ;;; ffap.el ends here