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