Fix documentation of forward-line
[emacs.git] / lisp / ffap.el
blobd78fd4c4b31030c5b0860b8ac0fcc6fe8b69af8a
1 ;;; ffap.el --- find file (or url) at point
3 ;; Copyright (C) 1995-1997, 2000-2015 Free Software Foundation, Inc.
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/
11 ;; This file is part of GNU Emacs.
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.
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.
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/>.
27 ;;; Commentary:
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.
37 ;; For the default installation, add this line to your init file:
39 ;; (ffap-bindings) ; do default key bindings
41 ;; ffap-bindings makes the following global key bindings:
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
47 ;; C-x d dired-at-point
48 ;; C-x C-d ffap-list-directory
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
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
58 ;; S-mouse-3 ffap-at-mouse
59 ;; C-S-mouse-3 ffap-menu
61 ;; ffap-bindings also adds hooks to make the following local bindings
62 ;; in vm, gnus, and rmail:
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")
67 ;; If you do not like these bindings, modify the variable
68 ;; `ffap-bindings', or write your own.
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:
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
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.
86 ;;; Change Log:
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.
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
106 ;;; Code:
108 (require 'url-parse)
109 (require 'thingatpt)
111 (define-obsolete-variable-alias 'ffap-version 'emacs-version "23.2")
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)
120 ;; The code is organized in pages, separated by formfeed characters.
121 ;; See the next two pages for standard customization ideas.
124 ;;; User Variables:
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))
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)
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)
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)
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")
166 (defcustom ffap-lax-url nil
167 "If non-nil, allow lax URL matching."
168 :type 'boolean
169 :group 'ffap
170 :version "25.1")
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)
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)
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.")
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
205 :group 'ffap)
208 ;;; Peanut Gallery (More User Variables):
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.
216 (defcustom ffap-dired-wildcards "[*?][^/]*\\'"
217 "A regexp matching filename wildcard characters, or nil.
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'.
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
234 :group 'ffap)
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)
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)
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)
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)
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)
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)
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))))
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)
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")
297 ;;; Compatibility:
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.
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))))
309 ;;; Find Next Thing in buffer (`ffap-next'):
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.
315 (defvar ffap-next-guess nil
316 "Last value returned by `ffap-next-guess'.")
318 (defvar ffap-string-at-point-region '(1 1)
319 "List (BEG END), last region returned by the function `ffap-string-at-point'.")
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)))
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 ")))))
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))))
371 ;;; Machines (`ffap-machine-p'):
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)
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))))
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
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)
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")))
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))))))))))))
477 ;;; Possibly Remote Resources:
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")
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))))
494 (defvar ffap-compression-suffixes '(".gz" ".Z") ; .z is mostly dead
495 "List of suffixes tried by `ffap-file-exists-string'.")
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))))
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)))
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)))
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")
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 ":"))))
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))
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)
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))))))
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))))
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))))
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)))
625 ;;; File Name Handling:
627 ;; The upcoming ffap-alist actions need various utilities to prepare
628 ;; and search directories. Too many features here.
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)))
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)))
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)))
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))))
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 )))))
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.")
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)))
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.
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))
750 ;;; Action List (`ffap-alist'):
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.
757 (defvar ffap-alist
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
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.")
794 (put 'ffap-alist 'risky-local-variable t)
796 ;; Example `ffap-alist' modifications:
798 ;; (setq ffap-alist ; remove a feature in `ffap-alist'
799 ;; (delete (assoc 'c-mode ffap-alist) ffap-alist))
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))
812 ;;; Action Definitions:
814 ;; Define various default members of `ffap-alist'.
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))))
821 (defun ffap-home (name) (ffap-locate-file name t '("~")))
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)
830 (defun ffap-info-2 (name) (ffap-info (substring name 5)))
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)))
836 (defun ffap-el (name) (ffap-locate-file name t load-path))
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)))
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.")
862 (defun ffap-c-mode (name)
863 (ffap-locate-file name t ffap-c-path))
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.")
884 (defun ffap-c++-mode (name)
885 (ffap-locate-file name t ffap-c++-path))
887 (defvar ffap-fortran-path '("../include" "/usr/include"))
889 (defun ffap-fortran-mode (name)
890 (ffap-locate-file name t ffap-fortran-path))
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.")
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
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")))))))))
915 (defun ffap-tex-mode (name)
916 (ffap-tex-init)
917 (ffap-locate-file name '(".tex" "") ffap-tex-path))
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))
924 (defun ffap-tex (name)
925 (ffap-tex-init)
926 (ffap-locate-file name t ffap-tex-path))
928 (defvar ffap-bib-path
929 (ffap-list-env "BIBINPUTS"
930 (ffap-reduce-path
932 ;; a few wild guesses, need better
933 "/usr/local/lib/tex/macros/bib" ; Solaris?
934 "/usr/lib/texmf/bibtex/bib" ; Linux?
935 ))))
937 (defun ffap-bib (name)
938 (ffap-locate-file name t ffap-bib-path))
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))))
956 ;; Maybe a "Lisp Code Directory" reference:
957 (defun ffap-lcd (name)
958 ;; FIXME: Is this still in use?
959 (and
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))))
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)
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)
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))))
999 ;;; At-Point Functions:
1001 (defvar ffap-string-at-point-mode-alist
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:]~`" "<" "@>;.,!?`:")
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.")
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'.")
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)))))
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
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))))
1085 ;; External.
1086 (declare-function w3-view-this-url "ext:w3" (&optional no-show))
1088 (defun ffap-url-at-point ()
1089 "Return URL from around point if it exists, or nil."
1090 (when ffap-url-regexp
1091 (or (and (eq major-mode 'w3-mode) ; In a w3 buffer button?
1092 (w3-view-this-url t))
1093 (let ((thing-at-point-beginning-of-url-regexp ffap-url-regexp)
1094 (thing-at-point-default-mail-uri-scheme ffap-foo-at-bar-prefix))
1095 (thing-at-point-url-at-point ffap-lax-url
1096 (if (use-region-p)
1097 (cons (region-beginning)
1098 (region-end))))))))
1100 (defvar ffap-gopher-regexp
1101 "^.*\\<\\(Type\\|Name\\|Path\\|Host\\|Port\\) *= *\\(.*\\) *$"
1102 "Regexp matching a line in a gopher bookmark (maybe indented).
1103 The two subexpressions are the KEY and VALUE.")
1105 (defun ffap-gopher-at-point ()
1106 "If point is inside a gopher bookmark block, return its URL."
1107 ;; `gopher-parse-bookmark' from gopher.el is not so robust
1108 (save-excursion
1109 (beginning-of-line)
1110 (if (looking-at ffap-gopher-regexp)
1111 (progn
1112 (while (and (looking-at ffap-gopher-regexp) (not (bobp)))
1113 (forward-line -1))
1114 (or (looking-at ffap-gopher-regexp) (forward-line 1))
1115 (let ((type "1") path host (port "70"))
1116 (while (looking-at ffap-gopher-regexp)
1117 (let ((var (intern
1118 (downcase
1119 (buffer-substring (match-beginning 1)
1120 (match-end 1)))))
1121 (val (buffer-substring (match-beginning 2)
1122 (match-end 2))))
1123 (set var val)
1124 (forward-line 1)))
1125 (if (and path (string-match "^ftp:.*@" path))
1126 (concat "ftp://"
1127 (substring path 4 (1- (match-end 0)))
1128 (substring path (match-end 0)))
1129 (and (= (length type) 1)
1130 host;; (ffap-machine-p host)
1131 (concat "gopher://" host
1132 (if (equal port "70") "" (concat ":" port))
1133 "/" type path))))))))
1135 (defvar ffap-ftp-sans-slash-regexp
1136 (and
1137 ffap-ftp-regexp
1138 ;; Note: by now, we know it is not an url.
1139 ;; Icky regexp avoids: default: 123: foo::bar cs:pub
1140 ;; It does match on: mic@cs: cs:/pub mathcs.emory.edu: (point at end)
1141 "\\`\\([^:@]+@[^:@]+:\\|[^@.:]+\\.[^@:]+:\\|[^:]+:[~/]\\)\\([^:]\\|\\'\\)")
1142 "Strings matching this are coerced to FTP file names by ffap.
1143 That is, ffap just prepends \"/\". Set to nil to disable.")
1145 (defun ffap-file-at-point ()
1146 "Return filename from around point if it exists, or nil.
1147 Existence test is skipped for names that look remote.
1148 If the filename is not obvious, it also tries `ffap-alist',
1149 which may actually result in an URL rather than a filename."
1150 ;; Note: this function does not need to look for url's, just
1151 ;; filenames. On the other hand, it is responsible for converting
1152 ;; a pseudo-url "site.com://dir" to an ftp file name
1153 (let* ((case-fold-search t) ; url prefixes are case-insensitive
1154 (data (match-data))
1155 (string (ffap-string-at-point)) ; uses mode alist
1156 (name
1157 (or (condition-case nil
1158 (and (not (string-match "//" string)) ; foo.com://bar
1159 (substitute-in-file-name string))
1160 (error nil))
1161 string))
1162 (abs (file-name-absolute-p name))
1163 (default-directory default-directory)
1164 (oname name))
1165 (unwind-protect
1166 (cond
1167 ;; Immediate rejects (/ and // and /* are too common in C/C++):
1168 ((member name '("" "/" "//" "/*" ".")) nil)
1169 ;; Immediately test local filenames. If default-directory is
1170 ;; remote, you probably already have a connection.
1171 ((and (not abs) (ffap-file-exists-string name)))
1172 ;; Try stripping off line numbers; good for compilation/grep output.
1173 ((and (not abs) (string-match ":[0-9]" name)
1174 (ffap-file-exists-string (substring name 0 (match-beginning 0)))))
1175 ;; Try stripping off prominent (non-root - #) shell prompts
1176 ;; if the ffap-shell-prompt-regexp is non-nil.
1177 ((and ffap-shell-prompt-regexp
1178 (not abs) (string-match ffap-shell-prompt-regexp name)
1179 (ffap-file-exists-string (substring name (match-end 0)))))
1180 ;; Accept remote names without actual checking (too slow):
1181 ((and abs (ffap-file-remote-p name)))
1182 ;; Ok, not remote, try the existence test even if it is absolute:
1183 ((and abs (ffap-file-exists-string name)))
1184 ;; Try stripping off line numbers.
1185 ((and abs (string-match ":[0-9]" name)
1186 (ffap-file-exists-string (substring name 0 (match-beginning 0)))))
1187 ;; If it contains a colon, get rid of it (and return if exists)
1188 ((and (string-match path-separator name)
1189 (setq name (ffap-string-at-point 'nocolon))
1190 (ffap-file-exists-string name)))
1191 ;; File does not exist, try the alist:
1192 ((let ((alist ffap-alist) tem try case-fold-search)
1193 (while (and alist (not try))
1194 (setq tem (car alist) alist (cdr alist))
1195 (if (or (eq major-mode (car tem))
1196 (and (stringp (car tem))
1197 (string-match (car tem) name)))
1198 (and (setq try
1199 (condition-case nil
1200 (funcall (cdr tem) name)
1201 (error nil)))
1202 (setq try (or
1203 (ffap-url-p try) ; not a file!
1204 (ffap-file-remote-p try)
1205 (ffap-file-exists-string try))))))
1206 try))
1207 ;; Try adding a leading "/" (common omission in ftp file names).
1208 ;; Note that this uses oname, which still has any colon part.
1209 ;; This should have a lower priority than the alist stuff,
1210 ;; else it matches things like "ffap.el:1234:56:Warning".
1211 ((and (not abs)
1212 ffap-ftp-sans-slash-regexp
1213 (string-match ffap-ftp-sans-slash-regexp oname)
1214 (ffap-file-remote-p (concat "/" oname))))
1215 ;; Alist failed? Try to guess an active remote connection
1216 ;; from buffer variables, and try once more, both as an
1217 ;; absolute and relative file name on that remote host.
1218 ((let* (ffap-rfs-regexp ; suppress
1219 (remote-dir
1220 (cond
1221 ((ffap-file-remote-p default-directory))
1222 ((and (eq major-mode 'internal-ange-ftp-mode)
1223 (string-match "^\\*ftp \\(.*\\)@\\(.*\\)\\*$"
1224 (buffer-name)))
1225 (concat "/" (substring (buffer-name) 5 -1) ":"))
1226 ;; This is too often a bad idea:
1227 ;;((and (eq major-mode 'w3-mode)
1228 ;; (stringp url-current-server))
1229 ;; (host-to-ange-path url-current-server))
1231 (and remote-dir
1233 (and (string-match "\\`\\(/?~?ftp\\)/" name)
1234 (ffap-file-exists-string
1235 (ffap-replace-file-component
1236 remote-dir (substring name (match-end 1)))))
1237 (ffap-file-exists-string
1238 (ffap-replace-file-component remote-dir name))))))
1239 ((and ffap-dired-wildcards
1240 (string-match ffap-dired-wildcards name)
1242 (ffap-file-exists-string (file-name-directory
1243 (directory-file-name name)))
1244 name))
1245 ;; Try all parent directories by deleting the trailing directory
1246 ;; name until existing directory is found or name stops changing
1247 ((let ((dir name))
1248 (while (and dir
1249 (not (ffap-file-exists-string dir))
1250 (not (equal dir (setq dir (file-name-directory
1251 (directory-file-name dir)))))))
1252 (and (not (string= dir "/"))
1253 (ffap-file-exists-string dir))))
1255 (set-match-data data))))
1257 ;;; Prompting (`ffap-read-file-or-url'):
1259 ;; We want to complete filenames as in read-file-name, but also url's
1260 ;; which read-file-name-internal would truncate at the "//" string.
1261 ;; The solution here is to replace read-file-name-internal with
1262 ;; `ffap-read-file-or-url-internal', which checks the minibuffer
1263 ;; contents before attempting to complete filenames.
1265 (defun ffap-read-file-or-url (prompt guess)
1266 "Read file or URL from minibuffer, with PROMPT and initial GUESS."
1267 (or guess (setq guess default-directory))
1268 (let (dir)
1269 ;; Tricky: guess may have or be a local directory, like "w3/w3.elc"
1270 ;; or "w3/" or "../el/ffap.el" or "../../../"
1271 (unless (ffap-url-p guess)
1272 (unless (ffap-file-remote-p guess)
1273 (setq guess
1274 (abbreviate-file-name (expand-file-name guess))))
1275 (setq dir (file-name-directory guess)))
1276 (let ((minibuffer-completing-file-name t)
1277 (completion-ignore-case read-file-name-completion-ignore-case)
1278 (fnh-elem (cons ffap-url-regexp 'url-file-handler)))
1279 ;; Explain to `rfn-eshadow' that we can use URLs here.
1280 (push fnh-elem file-name-handler-alist)
1281 (unwind-protect
1282 (setq guess
1283 (let ((default-directory (if dir (expand-file-name dir)
1284 default-directory)))
1285 (completing-read
1286 prompt
1287 'ffap-read-file-or-url-internal
1290 (if dir (cons guess (length dir)) guess)
1291 'file-name-history
1292 (and buffer-file-name
1293 (abbreviate-file-name buffer-file-name)))))
1294 ;; Remove the special handler manually. We used to just let-bind
1295 ;; file-name-handler-alist to preserve its value, but that caused
1296 ;; other modifications to be lost (e.g. when Tramp gets loaded
1297 ;; during the completing-read call).
1298 (setq file-name-handler-alist (delq fnh-elem file-name-handler-alist))))
1299 (or (ffap-url-p guess)
1300 (substitute-in-file-name guess))))
1302 (defun ffap-read-url-internal (string pred action)
1303 "Complete URLs from history, treating given string as valid."
1304 (let ((hist (ffap-symbol-value 'url-global-history-hash-table)))
1305 (cond
1306 ((not action)
1307 (or (try-completion string hist pred) string))
1308 ((eq action t)
1309 (or (all-completions string hist pred) (list string)))
1310 ;; action == lambda, documented where? Tests whether string is a
1311 ;; valid "match". Let us always say yes.
1312 (t t))))
1314 (defun ffap-read-file-or-url-internal (string pred action)
1315 (let ((url (ffap-url-p string)))
1316 (if url
1317 (ffap-read-url-internal url pred action)
1318 (read-file-name-internal (or string default-directory) pred action))))
1320 ;; The rest of this page is just to work with package complete.el.
1321 ;; This code assumes that you load ffap.el after complete.el.
1323 ;; We must inform complete about whether our completion function
1324 ;; will do filename style completion.
1327 ;;; Highlighting (`ffap-highlight'):
1329 (defvar ffap-highlight t
1330 "If non-nil, ffap highlights the current buffer substring.")
1332 (defface ffap
1333 '((t :inherit highlight))
1334 "Face used to highlight the current buffer substring."
1335 :group 'ffap
1336 :version "22.1")
1338 (defvar ffap-highlight-overlay nil
1339 "Overlay used by function `ffap-highlight'.")
1341 (defun ffap-highlight (&optional remove)
1342 "If `ffap-highlight' is set, highlight the guess in this buffer.
1343 That is, the last buffer substring found by `ffap-string-at-point'.
1344 Optional argument REMOVE means to remove any such highlighting.
1345 Uses the face `ffap' if it is defined, or else `highlight'."
1346 (cond
1347 (remove
1348 (and ffap-highlight-overlay
1349 (delete-overlay ffap-highlight-overlay))
1351 ((not ffap-highlight) nil)
1352 (ffap-highlight-overlay
1353 (move-overlay
1354 ffap-highlight-overlay
1355 (car ffap-string-at-point-region)
1356 (nth 1 ffap-string-at-point-region)
1357 (current-buffer)))
1359 (setq ffap-highlight-overlay
1360 (apply 'make-overlay ffap-string-at-point-region))
1361 (overlay-put ffap-highlight-overlay 'face 'ffap))))
1364 ;;; Main Entrance (`find-file-at-point' == `ffap'):
1366 (defun ffap-guesser ()
1367 "Return file or URL or nil, guessed from text around point."
1368 (or (and ffap-url-regexp
1369 (ffap-fixup-url (or (ffap-url-at-point)
1370 (ffap-gopher-at-point))))
1371 (ffap-file-at-point) ; may yield url!
1372 (ffap-fixup-machine (ffap-machine-at-point))))
1374 (defun ffap-prompter (&optional guess)
1375 ;; Does guess and prompt step for find-file-at-point.
1376 ;; Extra complication for the temporary highlighting.
1377 (unwind-protect
1378 ;; This catch will let ffap-alist entries do their own prompting
1379 ;; and then maybe skip over this prompt (ff-paths, for example).
1380 (catch 'ffap-prompter
1381 (ffap-read-file-or-url
1382 (if ffap-url-regexp "Find file or URL: " "Find file: ")
1383 (prog1
1384 (let ((mark-active nil))
1385 ;; Don't use the region here, since it can be something
1386 ;; completely unwieldy. If the user wants that, she could
1387 ;; use M-w before and then C-y. --Stef
1388 (setq guess (or guess (ffap-guesser)))) ; using ffap-alist here
1389 (and guess (ffap-highlight))
1391 (ffap-highlight t)))
1393 ;;;###autoload
1394 (defun find-file-at-point (&optional filename)
1395 "Find FILENAME, guessing a default from text around point.
1396 If `ffap-url-regexp' is not nil, the FILENAME may also be an URL.
1397 With a prefix, this command behaves exactly like `ffap-file-finder'.
1398 If `ffap-require-prefix' is set, the prefix meaning is reversed.
1399 See also the variables `ffap-dired-wildcards', `ffap-newfile-prompt',
1400 and the functions `ffap-file-at-point' and `ffap-url-at-point'."
1401 (interactive)
1402 (if (and (called-interactively-p 'interactive)
1403 (if ffap-require-prefix (not current-prefix-arg)
1404 current-prefix-arg))
1405 ;; Do exactly the ffap-file-finder command, even the prompting:
1406 (let (current-prefix-arg) ; we already interpreted it
1407 (call-interactively ffap-file-finder))
1408 (or filename (setq filename (ffap-prompter)))
1409 (let ((url (ffap-url-p filename)))
1410 (cond
1411 (url
1412 (let (current-prefix-arg)
1413 (funcall ffap-url-fetcher url)))
1414 ((and ffap-pass-wildcards-to-dired
1415 ffap-dired-wildcards
1416 (string-match ffap-dired-wildcards filename))
1417 (funcall ffap-directory-finder filename))
1418 ((and ffap-dired-wildcards
1419 (string-match ffap-dired-wildcards filename)
1420 find-file-wildcards
1421 ;; Check if it's find-file that supports wildcards arg
1422 (memq ffap-file-finder '(find-file find-alternate-file)))
1423 (funcall ffap-file-finder (expand-file-name filename) t))
1424 ((or (not ffap-newfile-prompt)
1425 (file-exists-p filename)
1426 (y-or-n-p "File does not exist, create buffer? "))
1427 (funcall ffap-file-finder
1428 ;; expand-file-name fixes "~/~/.emacs" bug sent by CHUCKR.
1429 (expand-file-name filename)))
1430 ;; User does not want to find a non-existent file:
1431 ((signal 'file-error (list "Opening file buffer"
1432 "No such file or directory"
1433 filename)))))))
1435 ;; Shortcut: allow {M-x ffap} rather than {M-x find-file-at-point}.
1436 ;;;###autoload
1437 (defalias 'ffap 'find-file-at-point)
1440 ;;; Menu support (`ffap-menu'):
1442 (defcustom ffap-menu-regexp nil
1443 "If non-nil, regexp overriding `ffap-next-regexp' in `ffap-menu'.
1444 Make this more restrictive for faster menu building.
1445 For example, try \":/\" for URL (and some FTP) references."
1446 :type '(choice (const nil) regexp)
1447 :group 'ffap)
1449 (defvar ffap-menu-alist nil
1450 "Buffer local cache of menu presented by `ffap-menu'.")
1451 (make-variable-buffer-local 'ffap-menu-alist)
1453 (defvar ffap-menu-text-plist
1454 (cond
1455 ((display-mouse-p) '(face bold mouse-face highlight)) ; keymap <mousy-map>
1456 (t nil))
1457 "Text properties applied to strings found by `ffap-menu-rescan'.
1458 These properties may be used to fontify the menu references.")
1460 ;;;###autoload
1461 (defun ffap-menu (&optional rescan)
1462 "Put up a menu of files and URLs mentioned in this buffer.
1463 Then set mark, jump to choice, and try to fetch it. The menu is
1464 cached in `ffap-menu-alist', and rebuilt by `ffap-menu-rescan'.
1465 The optional RESCAN argument (a prefix, interactively) forces
1466 a rebuild. Searches with `ffap-menu-regexp'."
1467 (interactive "P")
1468 ;; (require 'imenu) -- no longer used, but roughly emulated
1469 (if (or (not ffap-menu-alist) rescan
1470 ;; or if the first entry is wrong:
1471 (and ffap-menu-alist
1472 (let ((first (car ffap-menu-alist)))
1473 (save-excursion
1474 (goto-char (cdr first))
1475 (not (equal (car first) (ffap-guesser)))))))
1476 (ffap-menu-rescan))
1477 ;; Tail recursive:
1478 (ffap-menu-ask
1479 (if ffap-url-regexp "Find file or URL" "Find file")
1480 (cons (cons "*Rescan Buffer*" -1) ffap-menu-alist)
1481 'ffap-menu-cont))
1483 (defun ffap-menu-cont (choice) ; continuation of ffap-menu
1484 (if (< (cdr choice) 0)
1485 (ffap-menu t) ; *Rescan*
1486 (push-mark)
1487 (goto-char (cdr choice))
1488 ;; Momentary highlight:
1489 (unwind-protect
1490 (progn
1491 (and ffap-highlight (ffap-guesser) (ffap-highlight))
1492 (sit-for 0) ; display
1493 (find-file-at-point (car choice)))
1494 (ffap-highlight t))))
1496 (defun ffap-menu-ask (title alist cont)
1497 "Prompt from a menu of choices, and then apply some action.
1498 Arguments are TITLE, ALIST, and CONT (a continuation function).
1499 This uses either a menu or the minibuffer depending on invocation.
1500 The TITLE string is used as either the prompt or menu title.
1501 Each ALIST entry looks like (STRING . DATA) and defines one choice.
1502 Function CONT is applied to the entry chosen by the user."
1503 ;; Note: this function is used with a different continuation
1504 ;; by the ffap-url add-on package.
1505 ;; Could try rewriting to use easymenu.el or lmenu.el.
1506 (let (choice)
1507 (cond
1508 ;; Emacs mouse:
1509 ((and (fboundp 'x-popup-menu) (ffap-mouse-event))
1510 (setq choice
1511 (x-popup-menu
1513 (list "" (cons title
1514 (mapcar (lambda (i) (cons (car i) i))
1515 alist))))))
1516 ;; minibuffer with completion buffer:
1518 (let ((minibuffer-setup-hook 'minibuffer-completion-help))
1519 ;; Bug: prompting may assume unique strings, no "".
1520 (setq choice
1521 (completing-read
1522 (format "%s (default %s): " title (car (car alist)))
1523 alist nil t
1524 ;; (cons (car (car alist)) 0)
1525 nil)))
1526 (sit-for 0) ; redraw original screen
1527 ;; Convert string to its entry, or else the default:
1528 (setq choice (or (assoc choice alist) (car alist)))))
1529 (if choice
1530 (funcall cont choice)
1531 (message "No choice made!") ; possible with menus
1532 nil)))
1534 (defun ffap-menu-rescan ()
1535 "Search buffer for `ffap-menu-regexp' to build `ffap-menu-alist'.
1536 Applies `ffap-menu-text-plist' text properties at all matches."
1537 (interactive)
1538 (let ((ffap-next-regexp (or ffap-menu-regexp ffap-next-regexp))
1539 (range (- (point-max) (point-min)))
1540 (mod (buffer-modified-p)) ; was buffer modified?
1541 ;; inhibit-read-only works on read-only text properties
1542 ;; as well as read-only buffers.
1543 (inhibit-read-only t) ; to set text-properties
1544 item
1545 ;; Avoid repeated searches of the *mode-alist:
1546 (major-mode (if (assq major-mode ffap-string-at-point-mode-alist)
1547 major-mode
1548 'file)))
1549 (setq ffap-menu-alist nil)
1550 (unwind-protect
1551 (save-excursion
1552 (goto-char (point-min))
1553 (while (setq item (ffap-next-guess))
1554 (setq ffap-menu-alist (cons (cons item (point)) ffap-menu-alist))
1555 (add-text-properties (car ffap-string-at-point-region) (point)
1556 ffap-menu-text-plist)
1557 (message "Scanning...%2d%% <%s>"
1558 (/ (* 100 (- (point) (point-min))) range) item)))
1559 (or mod (restore-buffer-modified-p nil))))
1560 (message "Scanning...done")
1561 ;; Remove duplicates.
1562 (setq ffap-menu-alist ; sort by item
1563 (sort ffap-menu-alist
1564 (function
1565 (lambda (a b) (string-lessp (car a) (car b))))))
1566 (let ((ptr ffap-menu-alist)) ; remove duplicates
1567 (while (cdr ptr)
1568 (if (equal (car (car ptr)) (car (car (cdr ptr))))
1569 (setcdr ptr (cdr (cdr ptr)))
1570 (setq ptr (cdr ptr)))))
1571 (setq ffap-menu-alist ; sort by position
1572 (sort ffap-menu-alist
1573 (function
1574 (lambda (a b) (< (cdr a) (cdr b)))))))
1577 ;;; Mouse Support (`ffap-at-mouse'):
1579 ;; See the suggested binding in ffap-bindings (near eof).
1581 (defvar ffap-at-mouse-fallback nil ; ffap-menu? too time-consuming
1582 "Command invoked by `ffap-at-mouse' if nothing found at click, or nil.
1583 Ignored when `ffap-at-mouse' is called programmatically.")
1584 (put 'ffap-at-mouse-fallback 'risky-local-variable t)
1586 ;;;###autoload
1587 (defun ffap-at-mouse (e)
1588 "Find file or URL guessed from text around mouse click.
1589 Interactively, calls `ffap-at-mouse-fallback' if no guess is found.
1590 Return value:
1591 * if a guess string is found, return it (after finding it)
1592 * if the fallback is called, return whatever it returns
1593 * otherwise, nil"
1594 (interactive "e")
1595 (let ((guess
1596 ;; Maybe less surprising without the save-excursion?
1597 (save-excursion
1598 (mouse-set-point e)
1599 ;; Would prefer to do nothing unless click was *on* text. How
1600 ;; to tell that the click was beyond the end of current line?
1601 (ffap-guesser))))
1602 (cond
1603 (guess
1604 (set-buffer (ffap-event-buffer e))
1605 (ffap-highlight)
1606 (unwind-protect
1607 (progn
1608 (sit-for 0) ; display
1609 (message "Finding `%s'" guess)
1610 (find-file-at-point guess)
1611 guess) ; success: return non-nil
1612 (ffap-highlight t)))
1613 ((called-interactively-p 'interactive)
1614 (if ffap-at-mouse-fallback
1615 (call-interactively ffap-at-mouse-fallback)
1616 (message "No file or URL found at mouse click.")
1617 nil)) ; no fallback, return nil
1618 ;; failure: return nil
1622 ;;; ffap-other-*, ffap-read-only-*, ffap-alternate-* commands:
1624 ;; There could be a real `ffap-noselect' function, but we would need
1625 ;; at least two new user variables, and there is no w3-fetch-noselect.
1626 ;; So instead, we just fake it with a slow save-window-excursion.
1628 (defun ffap-other-window ()
1629 "Like `ffap', but put buffer in another window.
1630 Only intended for interactive use."
1631 (interactive)
1632 (let (value)
1633 (switch-to-buffer-other-window
1634 (save-window-excursion
1635 (setq value (call-interactively 'ffap))
1636 (unless (or (bufferp value) (bufferp (car-safe value)))
1637 (setq value (current-buffer)))
1638 (current-buffer)))
1639 value))
1641 (defun ffap-other-frame ()
1642 "Like `ffap', but put buffer in another frame.
1643 Only intended for interactive use."
1644 (interactive)
1645 ;; Extra code works around dedicated windows (noted by JENS, 7/96):
1646 (let* ((win (selected-window))
1647 (wdp (window-dedicated-p win))
1648 value)
1649 (unwind-protect
1650 (progn
1651 (set-window-dedicated-p win nil)
1652 (switch-to-buffer-other-frame
1653 (save-window-excursion
1654 (setq value (call-interactively 'ffap))
1655 (unless (or (bufferp value) (bufferp (car-safe value)))
1656 (setq value (current-buffer)))
1657 (current-buffer))))
1658 (set-window-dedicated-p win wdp))
1659 value))
1661 (defun ffap--toggle-read-only (buffer-or-list)
1662 (dolist (buffer (if (listp buffer-or-list)
1663 buffer-or-list
1664 (list buffer-or-list)))
1665 (with-current-buffer buffer
1666 (read-only-mode 1))))
1668 (defun ffap-read-only ()
1669 "Like `ffap', but mark buffer as read-only.
1670 Only intended for interactive use."
1671 (interactive)
1672 (let ((value (call-interactively 'ffap)))
1673 (unless (or (bufferp value) (bufferp (car-safe value)))
1674 (setq value (current-buffer)))
1675 (ffap--toggle-read-only value)
1676 value))
1678 (defun ffap-read-only-other-window ()
1679 "Like `ffap', but put buffer in another window and mark as read-only.
1680 Only intended for interactive use."
1681 (interactive)
1682 (let ((value (ffap-other-window)))
1683 (ffap--toggle-read-only value)
1684 value))
1686 (defun ffap-read-only-other-frame ()
1687 "Like `ffap', but put buffer in another frame and mark as read-only.
1688 Only intended for interactive use."
1689 (interactive)
1690 (let ((value (ffap-other-frame)))
1691 (ffap--toggle-read-only value)
1692 value))
1694 (defun ffap-alternate-file ()
1695 "Like `ffap' and `find-alternate-file'.
1696 Only intended for interactive use."
1697 (interactive)
1698 (let ((ffap-file-finder 'find-alternate-file))
1699 (call-interactively 'ffap)))
1701 (defun ffap-alternate-file-other-window ()
1702 "Like `ffap' and `find-alternate-file-other-window'.
1703 Only intended for interactive use."
1704 (interactive)
1705 (let ((ffap-file-finder 'find-alternate-file-other-window))
1706 (call-interactively 'ffap)))
1708 (defun ffap-literally ()
1709 "Like `ffap' and command `find-file-literally'.
1710 Only intended for interactive use."
1711 (interactive)
1712 (let ((ffap-file-finder 'find-file-literally))
1713 (call-interactively 'ffap)))
1715 (defalias 'find-file-literally-at-point 'ffap-literally)
1718 ;;; Bug Reporter:
1720 (define-obsolete-function-alias 'ffap-bug 'report-emacs-bug "23.1")
1721 (define-obsolete-function-alias 'ffap-submit-bug 'report-emacs-bug "23.1")
1724 ;;; Hooks for Gnus, VM, Rmail:
1726 ;; If you do not like these bindings, write versions with whatever
1727 ;; bindings you would prefer.
1729 (defun ffap-ro-mode-hook ()
1730 "Bind `ffap-next' and `ffap-menu' to M-l and M-m, resp."
1731 (local-set-key "\M-l" 'ffap-next)
1732 (local-set-key "\M-m" 'ffap-menu))
1734 (defun ffap-gnus-hook ()
1735 "Bind `ffap-gnus-next' and `ffap-gnus-menu' to M-l and M-m, resp."
1736 ;; message-id's
1737 (setq-local thing-at-point-default-mail-uri-scheme "news")
1738 ;; Note "l", "L", "m", "M" are taken:
1739 (local-set-key "\M-l" 'ffap-gnus-next)
1740 (local-set-key "\M-m" 'ffap-gnus-menu))
1742 (defvar gnus-summary-buffer)
1743 (defvar gnus-article-buffer)
1745 ;; This code is called from gnus.
1746 (declare-function gnus-summary-select-article "gnus-sum"
1747 (&optional all-headers force pseudo article))
1749 (declare-function gnus-configure-windows "gnus-win"
1750 (setting &optional force))
1752 (defun ffap-gnus-wrapper (form) ; used by both commands below
1753 (and (eq (current-buffer) (get-buffer gnus-summary-buffer))
1754 (gnus-summary-select-article)) ; get article of current line
1755 ;; Preserve selected buffer, but do not do save-window-excursion,
1756 ;; since we want to see any window created by the form. Temporarily
1757 ;; select the article buffer, so we can see any point movement.
1758 (let ((sb (window-buffer)))
1759 (gnus-configure-windows 'article)
1760 (pop-to-buffer gnus-article-buffer)
1761 (widen)
1762 ;; Skip headers for ffap-gnus-next (which will wrap around)
1763 (if (eq (point) (point-min)) (search-forward "\n\n" nil t))
1764 (unwind-protect
1765 (eval form)
1766 (pop-to-buffer sb))))
1768 (defun ffap-gnus-next ()
1769 "Run `ffap-next' in the gnus article buffer."
1770 (interactive) (ffap-gnus-wrapper '(ffap-next nil t)))
1772 (defun ffap-gnus-menu ()
1773 "Run `ffap-menu' in the gnus article buffer."
1774 (interactive) (ffap-gnus-wrapper '(ffap-menu)))
1778 ;;;###autoload
1779 (defun dired-at-point (&optional filename)
1780 "Start Dired, defaulting to file at point. See `ffap'.
1781 If `dired-at-point-require-prefix' is set, the prefix meaning is reversed."
1782 (interactive)
1783 (if (and (called-interactively-p 'interactive)
1784 (if dired-at-point-require-prefix
1785 (not current-prefix-arg)
1786 current-prefix-arg))
1787 (let (current-prefix-arg) ; already interpreted
1788 (call-interactively ffap-directory-finder))
1789 (or filename (setq filename (dired-at-point-prompter)))
1790 (let ((url (ffap-url-p filename)))
1791 (cond
1792 (url
1793 (funcall ffap-url-fetcher url))
1794 ((and ffap-dired-wildcards
1795 (string-match ffap-dired-wildcards filename))
1796 (funcall ffap-directory-finder filename))
1797 ((file-exists-p filename)
1798 (if (file-directory-p filename)
1799 (funcall ffap-directory-finder
1800 (expand-file-name filename))
1801 (funcall ffap-directory-finder
1802 (concat (expand-file-name filename) "*"))))
1803 ((and (file-writable-p
1804 (or (file-name-directory (directory-file-name filename))
1805 filename))
1806 (y-or-n-p "Directory does not exist, create it? "))
1807 (make-directory filename)
1808 (funcall ffap-directory-finder filename))
1809 ((error "No such file or directory `%s'" filename))))))
1811 (defun dired-at-point-prompter (&optional guess)
1812 ;; Does guess and prompt step for find-file-at-point.
1813 ;; Extra complication for the temporary highlighting.
1814 (unwind-protect
1815 (ffap-read-file-or-url
1816 (cond
1817 ((eq ffap-directory-finder 'list-directory)
1818 "List directory (brief): ")
1819 (ffap-url-regexp "Dired file or URL: ")
1820 (t "Dired file: "))
1821 (prog1
1822 (setq guess
1823 (let ((guess (or guess (ffap-guesser))))
1824 (cond
1825 ((null guess) nil)
1826 ((ffap-url-p guess))
1827 ((ffap-file-remote-p guess)
1828 guess)
1829 ((progn
1830 (setq guess (abbreviate-file-name
1831 (expand-file-name guess)))
1832 ;; Interpret local directory as a directory.
1833 (file-directory-p guess))
1834 (file-name-as-directory guess))
1835 ;; Get directory component from local files.
1836 ((file-regular-p guess)
1837 (file-name-directory guess))
1838 (guess))))
1839 (and guess (ffap-highlight))))
1840 (ffap-highlight t)))
1842 ;;; ffap-dired-other-*, ffap-list-directory commands:
1844 (defun ffap-dired-other-window ()
1845 "Like `dired-at-point', but put buffer in another window.
1846 Only intended for interactive use."
1847 (interactive)
1848 (let (value)
1849 (switch-to-buffer-other-window
1850 (save-window-excursion
1851 (setq value (call-interactively 'dired-at-point))
1852 (current-buffer)))
1853 value))
1855 (defun ffap-dired-other-frame ()
1856 "Like `dired-at-point', but put buffer in another frame.
1857 Only intended for interactive use."
1858 (interactive)
1859 ;; Extra code works around dedicated windows (noted by JENS, 7/96):
1860 (let* ((win (selected-window))
1861 (wdp (window-dedicated-p win))
1862 value)
1863 (unwind-protect
1864 (progn
1865 (set-window-dedicated-p win nil)
1866 (switch-to-buffer-other-frame
1867 (save-window-excursion
1868 (setq value (call-interactively 'dired-at-point))
1869 (current-buffer))))
1870 (set-window-dedicated-p win wdp))
1871 value))
1873 (defun ffap-list-directory ()
1874 "Like `dired-at-point' and `list-directory'.
1875 Only intended for interactive use."
1876 (interactive)
1877 (let ((ffap-directory-finder 'list-directory))
1878 (call-interactively 'dired-at-point)))
1881 ;;; Hooks to put in `file-name-at-point-functions':
1883 ;;;###autoload
1884 (defun ffap-guess-file-name-at-point ()
1885 "Try to get a file name at point.
1886 This hook is intended to be put in `file-name-at-point-functions'."
1887 (let ((guess (ffap-guesser)))
1888 (when (stringp guess)
1889 (let ((url (ffap-url-p guess)))
1890 (or url
1891 (progn
1892 (unless (ffap-file-remote-p guess)
1893 (setq guess
1894 (abbreviate-file-name (expand-file-name guess))))
1895 (if (file-directory-p guess)
1896 (file-name-as-directory guess)
1897 guess)))))))
1899 ;;; Offer default global bindings (`ffap-bindings'):
1901 (defvar ffap-bindings
1902 '((global-set-key [S-mouse-3] 'ffap-at-mouse)
1903 (global-set-key [C-S-mouse-3] 'ffap-menu)
1905 (global-set-key "\C-x\C-f" 'find-file-at-point)
1906 (global-set-key "\C-x\C-r" 'ffap-read-only)
1907 (global-set-key "\C-x\C-v" 'ffap-alternate-file)
1909 (global-set-key "\C-x4f" 'ffap-other-window)
1910 (global-set-key "\C-x5f" 'ffap-other-frame)
1911 (global-set-key "\C-x4r" 'ffap-read-only-other-window)
1912 (global-set-key "\C-x5r" 'ffap-read-only-other-frame)
1914 (global-set-key "\C-xd" 'dired-at-point)
1915 (global-set-key "\C-x4d" 'ffap-dired-other-window)
1916 (global-set-key "\C-x5d" 'ffap-dired-other-frame)
1917 (global-set-key "\C-x\C-d" 'ffap-list-directory)
1919 (add-hook 'gnus-summary-mode-hook 'ffap-gnus-hook)
1920 (add-hook 'gnus-article-mode-hook 'ffap-gnus-hook)
1921 (add-hook 'vm-mode-hook 'ffap-ro-mode-hook)
1922 (add-hook 'rmail-mode-hook 'ffap-ro-mode-hook))
1923 "List of binding forms evaluated by function `ffap-bindings'.
1924 A reasonable ffap installation needs just this one line:
1925 (ffap-bindings)
1926 Of course if you do not like these bindings, just roll your own!")
1928 ;;;###autoload
1929 (defun ffap-bindings ()
1930 "Evaluate the forms in variable `ffap-bindings'."
1931 (interactive)
1932 (eval (cons 'progn ffap-bindings)))
1935 (provide 'ffap)
1937 ;;; ffap.el ends here