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