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