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