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