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/>.
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
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.
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.
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
110 (define-obsolete-variable-alias 'ffap-version
'emacs-version
"23.2")
113 "Find file or URL at point."
115 ;; :link '(url-link :tag "URL" "ftp://ftp.mathcs.emory.edu/pub/mic/emacs/")
119 ;; The code is organized in pages, separated by formfeed characters.
120 ;; See the next two pages for standard customization ideas.
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.
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" "[$%><]*")
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" "\\`/[^/:]+:")
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'."
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
)
165 (defcustom ffap-lax-url t
166 "If non-nil, allow lax URL matching.
167 The default non-nil value might produce false URLs in C++ code
168 with symbols like \"std::find\". On the other hand, setting
169 this to nil will disable recognition of URLs that are not
170 well-formed, such as \"user@host\" or \"<user@host>\"."
175 (defcustom ffap-ftp-default-user
"anonymous"
176 "User name in FTP file names generated by `ffap-host-to-path'.
177 Note this name may be omitted if it equals the default
178 \(either `efs-default-user' or `ange-ftp-default-user')."
182 (defcustom ffap-rfs-regexp
183 ;; Remote file access built into file system? HP rfa or Andrew afs:
184 "\\`/\\(afs\\|net\\)/."
185 ;; afs only: (and (file-exists-p "/afs") "\\`/afs/.")
186 "Matching file names are treated as remote. Use nil to disable."
190 (defvar ffap-url-regexp
193 "news\\(post\\)?:\\|mailto:\\|file:" ; no host ok
195 "\\(ftp\\|https?\\|telnet\\|gopher\\|www\\|wais\\)://" ; needs host
197 "Regexp matching the beginning of a URI, for ffap.
198 If the value is nil, disable URL-matching features in ffap.")
200 (defcustom ffap-foo-at-bar-prefix
"mailto"
201 "Presumed URL prefix type of strings like \"<foo.9z@bar>\".
202 Sensible values are nil, \"news\", or \"mailto\"."
203 :type
'(choice (const "mailto")
205 (const :tag
"Disable" nil
)
206 ;; string -- possible, but not really useful
211 ;;; Peanut Gallery (More User Variables):
213 ;; Users of ffap occasionally suggest new features. If I consider
214 ;; those features interesting but not clear winners (a matter of
215 ;; personal taste) I try to leave options to enable them. Read
216 ;; through this section for features that you like, put an appropriate
217 ;; enabler in your init file.
219 (defcustom ffap-dired-wildcards
"[*?][^/]*\\'"
220 "A regexp matching filename wildcard characters, or nil.
222 If `find-file-at-point' gets a filename matching this pattern,
223 and `ffap-pass-wildcards-to-dired' is nil, it passes it on to
224 `find-file' with non-nil WILDCARDS argument, which expands
225 wildcards and visits multiple files. To visit a file whose name
226 contains wildcard characters you can suppress wildcard expansion
227 by setting `find-file-wildcards'. If `find-file-at-point' gets a
228 filename matching this pattern and `ffap-pass-wildcards-to-dired'
229 is non-nil, it passes it on to `dired'.
231 If `dired-at-point' gets a filename matching this pattern,
232 it passes it on to `dired'."
233 :type
'(choice (const :tag
"Disable" nil
)
234 (const :tag
"Enable" "[*?][^/]*\\'")
235 ;; regexp -- probably not useful
239 (defcustom ffap-pass-wildcards-to-dired nil
240 "If non-nil, pass filenames matching `ffap-dired-wildcards' to Dired."
244 (defcustom ffap-newfile-prompt nil
245 ;; Suggestion from RHOGEE, 11 Jul 1994. Disabled, I think this is
246 ;; better handled by `find-file-not-found-hooks'.
247 "Whether `find-file-at-point' prompts about a nonexistent file."
251 (defcustom ffap-require-prefix nil
252 ;; Suggestion from RHOGEE, 20 Oct 1994.
253 "If set, reverses the prefix argument to `find-file-at-point'.
254 This is nil so neophytes notice ffap. Experts may prefer to disable
255 ffap most of the time."
259 (defcustom ffap-file-finder
'find-file
260 "The command called by `find-file-at-point' to find a file."
265 (defcustom ffap-directory-finder
'dired
266 "The command called by `dired-at-point' to find a directory."
271 (defcustom ffap-url-fetcher
'browse-url
272 "A function of one argument, called by ffap to fetch an URL.
273 For a fancy alternative, get `ffap-url.el'."
274 :type
'(choice (const browse-url
)
279 (defcustom ffap-next-regexp
280 ;; If you want ffap-next to find URL's only, try this:
281 ;; (and ffap-url-regexp (string-match "\\\\`" ffap-url-regexp)
282 ;; (concat "\\<" (substring ffap-url-regexp 2))))
284 ;; It pays to put a big fancy regexp here, since ffap-guesser is
285 ;; much more time-consuming than regexp searching:
286 "[/:.~[:alpha:]]/\\|@[[:alpha:]][-[:alnum:]]*\\."
287 "Regular expression governing movements of `ffap-next'."
291 (defcustom dired-at-point-require-prefix nil
292 "If non-nil, reverse the prefix argument to `dired-at-point'.
293 This is nil so neophytes notice ffap. Experts may prefer to
294 disable ffap most of the time."
302 ;; This version of ffap supports only the Emacs it is distributed in.
303 ;; See the ftp site for a more general version. The following
304 ;; functions are necessary "leftovers" from the more general version.
306 (defun ffap-mouse-event () ; current mouse event, or nil
307 (and (listp last-nonmenu-event
) last-nonmenu-event
))
308 (defun ffap-event-buffer (event)
309 (window-buffer (car (event-start event
))))
312 ;;; Find Next Thing in buffer (`ffap-next'):
314 ;; Original ffap-next-url (URL's only) from RPECK 30 Mar 1995. Since
315 ;; then, broke it up into ffap-next-guess (noninteractive) and
316 ;; ffap-next (a command). It now work on files as well as url's.
318 (defvar ffap-next-guess nil
319 "Last value returned by `ffap-next-guess'.")
321 (defvar ffap-string-at-point-region
'(1 1)
322 "List (BEG END), last region returned by the function `ffap-string-at-point'.")
324 (defun ffap-next-guess (&optional back lim
)
325 "Move point to next file or URL, and return it as a string.
326 If nothing is found, leave point at limit and return nil.
327 Optional BACK argument makes search backwards.
328 Optional LIM argument limits the search.
329 Only considers strings that match `ffap-next-regexp'."
330 (or lim
(setq lim
(if back
(point-min) (point-max))))
332 (while (not (or guess
(eq (point) lim
)))
333 (funcall (if back
're-search-backward
're-search-forward
)
334 ffap-next-regexp lim
'move
)
335 (setq guess
(ffap-guesser)))
336 ;; Go to end, so we do not get same guess twice:
337 (goto-char (nth (if back
0 1) ffap-string-at-point-region
))
338 (setq ffap-next-guess guess
)))
341 (defun ffap-next (&optional back wrap
)
342 "Search buffer for next file or URL, and run ffap.
343 Optional argument BACK says to search backwards.
344 Optional argument WRAP says to try wrapping around if necessary.
345 Interactively: use a single prefix \\[universal-argument] to search backwards,
346 double prefix to wrap forward, triple to wrap backwards.
347 Actual search is done by the function `ffap-next-guess'."
349 (cdr (assq (prefix-numeric-value current-prefix-arg
)
350 '((1) (4 t
) (16 nil t
) (64 t t
)))))
352 (guess (ffap-next-guess back
)))
353 ;; Try wraparound if necessary:
354 (and (not guess
) wrap
355 (goto-char (if back
(point-max) (point-min)))
356 (setq guess
(ffap-next-guess back pt
)))
359 (sit-for 0) ; display point movement
360 (find-file-at-point (ffap-prompter guess
)))
361 (goto-char pt
) ; restore point
362 (message "No %sfiles or URL's found"
363 (if wrap
"" "more ")))))
365 (defun ffap-next-url (&optional back wrap
)
366 "Like `ffap-next', but search with `ffap-url-regexp'."
368 (let ((ffap-next-regexp ffap-url-regexp
))
369 (if (called-interactively-p 'interactive
)
370 (call-interactively 'ffap-next
)
371 (ffap-next back wrap
))))
374 ;;; Machines (`ffap-machine-p'):
376 ;; I cannot decide a "best" strategy here, so these are variables. In
377 ;; particular, if `Pinging...' is broken or takes too long on your
378 ;; machine, try setting these all to accept or reject.
379 (defcustom ffap-machine-p-local
'reject
; this happens often
380 "What `ffap-machine-p' does with hostnames that have no domain.
381 Value should be a symbol, one of `ping', `accept', and `reject'."
382 :type
'(choice (const ping
)
386 (defcustom ffap-machine-p-known
'ping
; `accept' for higher speed
387 "What `ffap-machine-p' does with hostnames that have a known domain.
388 Value should be a symbol, one of `ping', `accept', and `reject'.
389 See `mail-extr.el' for the known domains."
390 :type
'(choice (const ping
)
394 (defcustom ffap-machine-p-unknown
'reject
395 "What `ffap-machine-p' does with hostnames that have an unknown domain.
396 Value should be a symbol, one of `ping', `accept', and `reject'.
397 See `mail-extr.el' for the known domains."
398 :type
'(choice (const ping
)
403 (defun ffap-what-domain (domain)
404 ;; Like what-domain in mail-extr.el, returns string or nil.
406 (let ((ob (or (ffap-symbol-value 'mail-extr-all-top-level-domains
)
407 (ffap-symbol-value 'all-top-level-domains
)))) ; XEmacs
408 (and ob
(get (intern-soft (downcase domain
) ob
) 'domain-name
))))
410 (defun ffap-machine-p (host &optional service quiet strategy
)
411 "Decide whether HOST is the name of a real, reachable machine.
412 Depending on the domain (none, known, or unknown), follow the strategy
413 named by the variable `ffap-machine-p-local', `ffap-machine-p-known',
414 or `ffap-machine-p-unknown'. Pinging uses `open-network-stream'.
415 Optional SERVICE specifies the port used (default \"discard\").
416 Optional QUIET flag suppresses the \"Pinging...\" message.
417 Optional STRATEGY overrides the three variables above.
419 t means that HOST answered.
420 `accept' means the relevant variable told us to accept.
421 \"mesg\" means HOST exists, but does not respond for some reason."
422 ;; Try some (Emory local):
423 ;; (ffap-machine-p "ftp" nil nil 'ping)
424 ;; (ffap-machine-p "nonesuch" nil nil 'ping)
425 ;; (ffap-machine-p "ftp.mathcs.emory.edu" nil nil 'ping)
426 ;; (ffap-machine-p "mathcs" 5678 nil 'ping)
427 ;; (ffap-machine-p "foo.bonk" nil nil 'ping)
428 ;; (ffap-machine-p "foo.bonk.com" nil nil 'ping)
429 (if (or (string-match "[^-[:alnum:].]" host
) ; Invalid chars (?)
430 (not (string-match "[^0-9]" host
))) ; 1: a number? 2: quick reject
433 (and (string-match "\\.[^.]*$" host
)
434 (downcase (substring host
(1+ (match-beginning 0))))))
435 (what-domain (if domain
(ffap-what-domain domain
) "Local")))
438 (cond ((not domain
) ffap-machine-p-local
)
439 ((not what-domain
) ffap-machine-p-unknown
)
440 (t ffap-machine-p-known
))))
442 ((eq strategy
'accept
) 'accept
)
443 ((eq strategy
'reject
) nil
)
444 ((not (fboundp 'open-network-stream
)) nil
)
445 ;; assume (eq strategy 'ping)
448 (if (stringp what-domain
)
449 (message "Pinging %s (%s)..." host what-domain
)
450 (message "Pinging %s ..." host
)))
451 (condition-case error
455 "ffap-machine-p" nil host
(or service
"discard")))
458 (let ((mesg (car (cdr error
))))
461 ((string-match "\\(^Unknown host\\|Name or service not known$\\)"
463 ((string-match "not responding$" mesg
) mesg
)
465 ;; (file-error "connection failed" "permission denied"
466 ;; "nonesuch" "ffap-machine-p")
467 ;; (file-error "connection failed" "host is unreachable"
468 ;; "gopher.house.gov" "ffap-machine-p")
469 ;; (file-error "connection failed" "address already in use"
470 ;; "ftp.uu.net" "ffap-machine-p")
471 ((equal mesg
"connection failed")
472 (if (string= (downcase (nth 2 error
)) "permission denied")
473 nil
; host does not exist
474 ;; Other errors mean the host exists:
476 ;; Could be "Unknown service":
477 (t (signal (car error
) (cdr error
))))))))))))
480 ;;; Possibly Remote Resources:
482 (defun ffap-replace-file-component (fullname name
)
483 "In remote FULLNAME, replace path with NAME. May return nil."
484 ;; Use efs if loaded, but do not load it otherwise.
485 (if (fboundp 'efs-replace-path-component
)
486 (funcall 'efs-replace-path-component fullname name
)
487 (and (stringp fullname
)
489 (concat (file-remote-p fullname
) name
))))
490 ;; (ffap-replace-file-component "/who@foo.com:/whatever" "/new")
492 (defun ffap-file-suffix (file)
493 "Return trailing `.foo' suffix of FILE, or nil if none."
494 (let ((pos (string-match "\\.[^./]*\\'" file
)))
495 (and pos
(substring file pos nil
))))
497 (defvar ffap-compression-suffixes
'(".gz" ".Z") ; .z is mostly dead
498 "List of suffixes tried by `ffap-file-exists-string'.")
500 (defun ffap-file-exists-string (file &optional nomodify
)
501 ;; Early jka-compr versions modified file-exists-p to return the
502 ;; filename, maybe modified by adding a suffix like ".gz". That
503 ;; broke the interface of file-exists-p, so it was later dropped.
504 ;; Here we document and simulate the old behavior.
505 "Return FILE (maybe modified) if the file exists, else nil.
506 When using jka-compr (a.k.a. `auto-compression-mode'), the returned
507 name may have a suffix added from `ffap-compression-suffixes'.
508 The optional NOMODIFY argument suppresses the extra search."
510 ((not file
) nil
) ; quietly reject nil
511 ((file-exists-p file
) file
) ; try unmodified first
512 ;; three reasons to suppress search:
514 ((not (rassq 'jka-compr-handler file-name-handler-alist
)) nil
)
515 ((member (ffap-file-suffix file
) ffap-compression-suffixes
) nil
)
516 (t ; ok, do the search
517 (let ((list ffap-compression-suffixes
) try ret
)
519 (if (file-exists-p (setq try
(concat file
(car list
))))
520 (setq ret try list nil
)
521 (setq list
(cdr list
))))
524 (defun ffap-file-remote-p (filename)
525 "If FILENAME looks remote, return it (maybe slightly improved)."
526 ;; (ffap-file-remote-p "/user@foo.bar.com:/pub")
527 ;; (ffap-file-remote-p "/cssun.mathcs.emory.edu://dir")
528 ;; (ffap-file-remote-p "/ffap.el:80")
529 (or (and ffap-ftp-regexp
530 (string-match ffap-ftp-regexp filename
)
531 ;; Convert "/host.com://dir" to "/host:/dir", to handle a dying
532 ;; practice of advertising ftp files as "host.dom://filename".
533 (if (string-match "//" filename
)
534 ;; (replace-match "/" nil nil filename)
535 (concat (substring filename
0 (1+ (match-beginning 0)))
536 (substring filename
(match-end 0)))
539 (string-match ffap-rfs-regexp filename
)
542 (defun ffap-machine-at-point ()
543 "Return machine name at point if it exists, or nil."
544 (let ((mach (ffap-string-at-point 'machine
)))
545 (and (ffap-machine-p mach
) mach
)))
547 (defsubst ffap-host-to-filename
(host)
548 "Convert HOST to something like \"/USER@HOST:\" or \"/HOST:\".
549 Looks at `ffap-ftp-default-user', returns \"\" for \"localhost\"."
550 (if (equal host
"localhost")
552 (let ((user ffap-ftp-default-user
))
553 ;; Avoid including the user if it is same as default:
554 (if (or (equal user
(ffap-symbol-value 'ange-ftp-default-user
))
555 (equal user
(ffap-symbol-value 'efs-default-user
)))
557 (concat "/" user
(and user
"@") host
":"))))
559 (defun ffap-fixup-machine (mach)
560 ;; Convert a hostname into an url, an ftp file name, or nil.
562 ((not (and ffap-url-regexp
(stringp mach
))) nil
)
564 ((string-match "\\`gopher[-.]" mach
) ; or "info"?
565 (concat "gopher://" mach
"/"))
567 ((and (string-match "\\`w\\(ww\\|eb\\)[-.]" mach
))
568 (concat "http://" mach
"/"))
569 ;; More cases? Maybe "telnet:" for archie?
570 (ffap-ftp-regexp (ffap-host-to-filename mach
))
573 (defvaralias 'ffap-newsgroup-regexp
'thing-at-point-newsgroup-regexp
)
574 (defvaralias 'ffap-newsgroup-heads
'thing-at-point-newsgroup-heads
)
575 (defalias 'ffap-newsgroup-p
'thing-at-point-newsgroup-p
)
577 (defsubst ffap-url-p
(string)
578 "If STRING looks like an URL, return it (maybe improved), else nil."
579 (when (and (stringp string
) ffap-url-regexp
)
580 (let* ((case-fold-search t
)
581 (match (string-match ffap-url-regexp string
)))
582 (cond ((eq match
0) string
)
583 (match (substring string match
))))))
585 ;; Broke these out of ffap-fixup-url, for use of ffap-url package.
586 (defun ffap-url-unwrap-local (url)
587 "Return URL as a local file name, or nil."
588 (let* ((obj (url-generic-parse-url url
))
589 (host (url-host obj
))
590 (filename (car (url-path-and-query obj
))))
591 (when (and (member (url-type obj
) '("ftp" "file"))
592 (member host
`("" "localhost" ,(system-name))))
593 ;; On Windows, "file:///C:/foo" should unwrap to "C:/foo"
594 (if (and (memq system-type
'(ms-dos windows-nt cygwin
))
595 (string-match "\\`/[a-zA-Z]:" filename
))
596 (substring filename
1)
599 (defun ffap-url-unwrap-remote (url)
600 "Return URL as a remote file name, or nil."
601 (let* ((obj (url-generic-parse-url url
))
602 (scheme (url-type obj
))
603 (valid-schemes (if (listp ffap-url-unwrap-remote
)
604 ffap-url-unwrap-remote
606 (host (url-host obj
))
607 (port (url-port-if-non-default obj
))
608 (user (url-user obj
))
609 (filename (car (url-path-and-query obj
))))
610 (when (and (member scheme valid-schemes
)
611 (string-match "\\`[a-zA-Z][-a-zA-Z0-9+.]*\\'" scheme
)
612 (not (equal host
"")))
613 (concat "/" scheme
":"
614 (if user
(concat user
"@"))
616 (if port
(concat "#" (number-to-string port
)))
619 (defun ffap-fixup-url (url)
620 "Clean up URL and return it, maybe as a file name."
622 ((not (stringp url
)) nil
)
623 ((and ffap-url-unwrap-local
(ffap-url-unwrap-local url
)))
624 ((and ffap-url-unwrap-remote
(ffap-url-unwrap-remote url
)))
628 ;;; File Name Handling:
630 ;; The upcoming ffap-alist actions need various utilities to prepare
631 ;; and search directories. Too many features here.
633 ;; (defun ffap-last (l) (while (cdr l) (setq l (cdr l))) l)
634 ;; (defun ffap-splice (func inlist)
635 ;; "Equivalent to (apply 'nconc (mapcar FUNC INLIST)), but less consing."
636 ;; (let* ((head (cons 17 nil)) (last head))
638 ;; (setcdr last (funcall func (car inlist)))
639 ;; (setq last (ffap-last last) inlist (cdr inlist)))
642 (defun ffap-list-env (env &optional empty
)
643 "Return a list of strings parsed from environment variable ENV.
644 Optional EMPTY is the default list if (getenv ENV) is undefined, and
645 also is substituted for the first empty-string component, if there is one.
646 Uses `path-separator' to separate the path into substrings."
647 ;; We cannot use parse-colon-path (files.el), since it kills
648 ;; "//" entries using file-name-as-directory.
649 ;; Similar: dired-split, TeX-split-string, and RHOGEE's psg-list-env
650 ;; in ff-paths and bib-cite. The EMPTY arg may help mimic kpathsea.
651 (if (or empty
(getenv env
)) ; should return something
652 (let ((start 0) match dir ret
)
653 (setq env
(concat (getenv env
) path-separator
))
654 (while (setq match
(string-match path-separator env start
))
655 (setq dir
(substring env start match
) start
(1+ match
))
656 ;;(and (file-directory-p dir) (not (member dir ret)) ...)
657 (setq ret
(cons dir ret
)))
658 (setq ret
(nreverse ret
))
659 (and empty
(setq match
(member "" ret
))
660 (progn ; allow string or list here
661 (setcdr match
(append (cdr-safe empty
) (cdr match
)))
662 (setcar match
(or (car-safe empty
) empty
))))
665 (defun ffap-reduce-path (path)
666 "Remove duplicates and non-directories from PATH list."
669 (setq tem path path
(cdr path
))
670 (if (equal (car tem
) ".") (setcar tem
""))
671 (or (member (car tem
) ret
)
672 (not (file-directory-p (car tem
)))
673 (progn (setcdr tem ret
) (setq ret tem
))))
676 (defun ffap-all-subdirs (dir &optional depth
)
677 "Return list of all subdirectories under DIR, starting with itself.
678 Directories beginning with \".\" are ignored, and directory symlinks
679 are listed but never searched (to avoid loops).
680 Optional DEPTH limits search depth."
681 (and (file-exists-p dir
)
682 (ffap-all-subdirs-loop (expand-file-name dir
) (or depth -
1))))
684 (defun ffap-all-subdirs-loop (dir depth
) ; internal
685 (setq depth
(1- depth
))
687 (and (not (eq depth -
1))
693 ((not (file-directory-p d
)) nil
)
694 ((file-symlink-p d
) (list d
))
695 (t (ffap-all-subdirs-loop d depth
)))))
696 (directory-files dir t
"\\`[^.]")
699 (defvar ffap-kpathsea-depth
1
700 "Bound on depth of subdirectory search in `ffap-kpathsea-expand-path'.
701 Set to 0 to avoid all searching, or nil for no limit.")
703 (defun ffap-kpathsea-expand-path (path)
704 "Replace each \"//\"-suffixed dir in PATH by a list of its subdirs.
705 The subdirs begin with the original directory, and the depth of the
706 search is bounded by `ffap-kpathsea-depth'. This is intended to mimic
707 kpathsea, a library used by some versions of TeX."
712 (if (string-match "[^/]//\\'" dir
)
713 (ffap-all-subdirs (substring dir
0 -
2) ffap-kpathsea-depth
)
717 (defun ffap-locate-file (file nosuffix path
)
718 ;; The current version of locate-library could almost replace this,
719 ;; except it does not let us override the suffix list. The
720 ;; compression-suffixes search moved to ffap-file-exists-string.
721 "A generic path-searching function.
722 Returns the name of file in PATH, or nil.
723 Optional NOSUFFIX, if nil or t, is like the fourth argument
724 for `load': whether to try the suffixes (\".elc\" \".el\" \"\").
725 If a nonempty list, it is a list of suffixes to try instead.
726 PATH is a list of directories.
728 This uses `ffap-file-exists-string', which may try adding suffixes from
729 `ffap-compression-suffixes'."
730 (if (file-name-absolute-p file
)
731 (setq path
(list (file-name-directory file
))
732 file
(file-name-nondirectory file
)))
733 (let ((dir-ok (equal "" (file-name-nondirectory file
)))
736 ((consp nosuffix
) nosuffix
)
738 (t '(".elc" ".el" ""))))
741 (setq suffixes suffixes-to-try
)
743 (setq try
(ffap-file-exists-string
745 (concat file
(car suffixes
)) (car path
))))
746 (if (and try
(or dir-ok
(not (file-directory-p try
))))
747 (setq found try suffixes nil path nil
)
748 (setq suffixes
(cdr suffixes
))))
749 (setq path
(cdr path
)))
753 ;;; Action List (`ffap-alist'):
755 ;; These search actions depend on the major-mode or regexps matching
756 ;; the current name. The little functions and their variables are
757 ;; deferred to the next section, at some loss of "code locality". A
758 ;; good example of featuritis. Trim this list for speed.
762 ("" . ffap-completable
) ; completion, slow on some systems
763 ("\\.info\\'" . ffap-info
) ; gzip.info
764 ("\\`info/" . ffap-info-2
) ; info/emacs
765 ("\\`[-[:lower:]]+\\'" . ffap-info-3
) ; (emacs)Top [only in the parentheses]
766 ("\\.elc?\\'" . ffap-el
) ; simple.el, simple.elc
767 (emacs-lisp-mode . ffap-el-mode
) ; rmail, gnus, simple, custom
768 ;; (lisp-interaction-mode . ffap-el-mode) ; maybe
769 (finder-mode . ffap-el-mode
) ; type {C-h p} and try it
770 (help-mode . ffap-el-mode
) ; maybe useful
771 (c++-mode . ffap-c
++-mode
) ; search ffap-c++-path
772 (cc-mode . ffap-c-mode
) ; same
773 ("\\.\\([chCH]\\|cc\\|hh\\)\\'" . ffap-c-mode
) ; stdio.h
774 (fortran-mode . ffap-fortran-mode
) ; FORTRAN requested by MDB
775 ("\\.[fF]\\'" . ffap-fortran-mode
)
776 (tex-mode . ffap-tex-mode
) ; search ffap-tex-path
777 (latex-mode . ffap-latex-mode
) ; similar
778 ("\\.\\(tex\\|sty\\|doc\\|cls\\)\\'" . ffap-tex
)
779 ("\\.bib\\'" . ffap-bib
) ; search ffap-bib-path
780 ("\\`\\." . ffap-home
) ; .emacs, .bashrc, .profile
781 ("\\`~/" . ffap-lcd
) ; |~/misc/ffap.el.Z|
782 ;; This used to have a blank, but ffap-string-at-point doesn't
784 ;; http://lists.gnu.org/archive/html/emacs-devel/2008-01/msg01058.html
785 ("\\`[Rr][Ff][Cc][-#]?\\([0-9]+\\)" ; no $
786 . ffap-rfc
) ; "100% RFC2100 compliant"
787 (dired-mode . ffap-dired
) ; maybe in a subdirectory
789 "Alist of (KEY . FUNCTION) pairs parsed by `ffap-file-at-point'.
790 If string NAME at point (maybe \"\") is not a file or URL, these pairs
791 specify actions to try creating such a string. A pair matches if either
792 KEY is a symbol, and it equals `major-mode', or
793 KEY is a string, it should match NAME as a regexp.
794 On a match, (FUNCTION NAME) is called and should return a file, an
795 URL, or nil. If nil, search the alist for further matches.
796 While calling FUNCTION, the match data is set according to KEY if KEY
797 is a string, so that FUNCTION can use `match-string' and friends
798 to extract substrings.")
800 (put 'ffap-alist
'risky-local-variable t
)
802 ;; Example `ffap-alist' modifications:
804 ;; (setq ffap-alist ; remove a feature in `ffap-alist'
805 ;; (delete (assoc 'c-mode ffap-alist) ffap-alist))
807 ;; (setq ffap-alist ; add something to `ffap-alist'
809 ;; (cons "^YSN[0-9]+$"
810 ;; (defun ffap-ysn (name)
812 ;; "http://www.physics.uiuc.edu/"
813 ;; "ysn/httpd/htdocs/ysnarchive/issuefiles/"
814 ;; (substring name 3) ".html")))
818 ;;; Action Definitions:
820 ;; Define various default members of `ffap-alist'.
822 (defun ffap-completable (name)
823 (let* ((dir (or (file-name-directory name
) default-directory
))
824 (cmp (file-name-completion (file-name-nondirectory name
) dir
)))
825 (and cmp
(concat dir cmp
))))
827 (defun ffap-home (name) (ffap-locate-file name t
'("~")))
829 (defun ffap-info (name)
832 (or (ffap-symbol-value 'Info-directory-list
)
833 (ffap-symbol-value 'Info-default-directory-list
)
836 (defun ffap-info-2 (name) (ffap-info (substring name
5)))
838 (defun ffap-info-3 (name)
839 ;; This ignores the node! "(emacs)Top" same as "(emacs)Intro"
840 (and (equal (ffap-string-around) "()") (ffap-info name
)))
842 (defun ffap-el (name) (ffap-locate-file name t load-path
))
844 (defun ffap-el-mode (name)
845 ;; If name == "foo.el" we will skip it, since ffap-el already
846 ;; searched for it once. (This assumes the default ffap-alist.)
847 (and (not (string-match "\\.el\\'" name
))
848 (ffap-locate-file name
'(".el") load-path
)))
850 ;; FIXME this duplicates the logic of Man-header-file-path.
851 ;; There should be a single central variable or function for this.
852 ;; See also (bug#10702):
853 ;; cc-search-directories, semantic-c-dependency-system-include-path,
854 ;; semantic-gcc-setup
856 (let ((arch (with-temp-buffer
857 (when (eq 0 (ignore-errors
858 (call-process "gcc" nil
'(t nil
) nil
859 "-print-multiarch")))
860 (goto-char (point-min))
861 (buffer-substring (point) (line-end-position)))))
862 (base '("/usr/include" "/usr/local/include")))
863 (if (zerop (length arch
))
865 (append base
(list (expand-file-name arch
"/usr/include")))))
866 "List of directories to search for include files.")
868 (defun ffap-c-mode (name)
869 (ffap-locate-file name t ffap-c-path
))
871 (defvar ffap-c
++-path
872 (let ((c++-include-dir
(with-temp-buffer
873 (when (eq 0 (ignore-errors
874 (call-process "g++" nil t nil
"-v")))
875 (goto-char (point-min))
876 (if (re-search-forward "--with-gxx-include-dir=\
880 (when (re-search-forward "gcc version \
881 \\([[:digit:]]+.[[:digit:]]+.[[:digit:]]+\\)"
883 (expand-file-name (match-string 1)
884 "/usr/include/c++/")))))))
886 (cons c
++-include-dir ffap-c-path
)
888 "List of directories to search for include files.")
890 (defun ffap-c++-mode
(name)
891 (ffap-locate-file name t ffap-c
++-path
))
893 (defvar ffap-fortran-path
'("../include" "/usr/include"))
895 (defun ffap-fortran-mode (name)
896 (ffap-locate-file name t ffap-fortran-path
))
898 (defvar ffap-tex-path
899 t
; delayed initialization
900 "Path where `ffap-tex-mode' looks for TeX files.
901 If t, `ffap-tex-init' will initialize this when needed.")
903 (defvar ffap-latex-guess-rules
'(("" .
".sty")
907 ("" .
"") ;; in some rare cases the
908 ;; extension is already in
910 ("beamertheme" .
".sty")
911 ("beamercolortheme".
".sty")
912 ("beamerfonttheme".
".sty")
913 ("beamerinnertheme".
".sty")
914 ("beameroutertheme".
".sty")
916 "List of rules for guessing a filename.
917 Each rule is a cons (PREFIX . SUFFIX) used for guessing a
918 filename from the word at point by prepending PREFIX and
921 (defun ffap-tex-init ()
922 ;; Compute ffap-tex-path if it is now t.
923 (and (eq t ffap-tex-path
)
924 ;; this may be slow, so say something
925 (message "Initializing ffap-tex-path ...")
930 (ffap-kpathsea-expand-path
932 (ffap-list-env "TEXINPUTS")
933 ;; (ffap-list-env "BIBINPUTS")
935 'TeX-macro-global
; AUCTeX
936 '("/usr/local/lib/tex/macros"
937 "/usr/local/lib/tex/inputs")))))))))
939 (defun ffap-tex-mode (name)
941 (ffap-locate-file name
'(".tex" "") ffap-tex-path
))
943 (defun ffap-latex-mode (name)
944 "`ffap' function suitable for latex buffers.
945 This uses the program kpsewhich if available. In this case, the
946 variable `ffap-latex-guess-rules' is used for building a filename
948 (cond ((file-exists-p name
)
950 ((not (executable-find "kpsewhich"))
952 (ffap-locate-file name
'(".cls" ".sty" ".tex" "") ffap-tex-path
))
954 (let ((curbuf (current-buffer))
955 (guess-rules ffap-latex-guess-rules
)
956 (preferred-suffix-rules '(("input" .
".tex")
958 ("usepackage" .
".sty")
959 ("RequirePackageWithOptions" .
".sty")
960 ("RequirePackage" .
".sty")
961 ("documentclass" .
".cls")
962 ("documentstyle" .
".cls")
963 ("LoadClass" .
".cls")
964 ("LoadClassWithOptions" .
".cls")
965 ("bibliography" .
".bib")
966 ("addbibresource" .
""))))
967 ;; We now add preferred suffix in front of suffixes.
969 ;; The condition is essentially:
970 ;; (assoc (TeX-current-macro)
971 ;; (mapcar 'car preferred-suffix-rules))
972 ;; but (TeX-current-macro) can take time, so we just
973 ;; check if one of the `car' in preferred-suffix-rules
974 ;; is found before point on the current line. It
975 ;; should cover most cases.
977 (re-search-backward (regexp-opt
978 (mapcar 'car preferred-suffix-rules
))
981 (push (cons "" (cdr (assoc (match-string 0) ; i.e. "(TeX-current-macro)"
982 preferred-suffix-rules
)))
985 (let ((process-environment (buffer-local-value
986 'process-environment curbuf
))
987 (exec-path (buffer-local-value 'exec-path curbuf
)))
988 (apply #'call-process
"kpsewhich" nil t nil
989 (mapcar (lambda (rule)
990 (concat (car rule
) name
(cdr rule
)))
992 (when (< (point-min) (point-max))
993 (buffer-substring (goto-char (point-min)) (point-at-eol))))))))
995 (defun ffap-tex (name)
997 (ffap-locate-file name t ffap-tex-path
))
999 (defvar ffap-bib-path
1000 (ffap-list-env "BIBINPUTS"
1003 ;; a few wild guesses, need better
1004 "/usr/local/lib/tex/macros/bib" ; Solaris?
1005 "/usr/lib/texmf/bibtex/bib" ; Linux?
1008 (defun ffap-bib (name)
1009 (ffap-locate-file name t ffap-bib-path
))
1011 (defun ffap-dired (name)
1012 (let ((pt (point)) try
)
1016 (looking-at " *[-d]r[-w][-x][-r][-w][-x][-r][-w][-x] "))
1017 (re-search-backward "^ *$" nil t
)
1018 (re-search-forward "^ *\\([^ \t\n:]*\\):\n *total " pt t
)
1024 (match-beginning 1) (match-end 1)))))
1027 ;; Maybe a "Lisp Code Directory" reference:
1028 (defun ffap-lcd (name)
1029 ;; FIXME: Is this still in use?
1032 ;; lisp-dir-apropos output buffer:
1033 (string-match "Lisp Code Dir" (buffer-name))
1034 ;; Inside an LCD entry like |~/misc/ffap.el.Z|,
1035 ;; or maybe the holy LCD-Datafile itself:
1036 (member (ffap-string-around) '("||" "|\n")))
1038 ;; lispdir.el may not be loaded yet:
1039 (ffap-host-to-filename
1040 (ffap-symbol-value 'elisp-archive-host
1041 "archive.cis.ohio-state.edu"))
1042 (file-name-as-directory
1043 (ffap-symbol-value 'elisp-archive-directory
1044 "/pub/gnu/emacs/elisp-archive/"))
1045 (substring name
2))))
1047 (defcustom ffap-rfc-path
1048 (concat (ffap-host-to-filename "ftp.rfc-editor.org") "/in-notes/rfc%s.txt")
1049 "A `format' string making a filename for RFC documents.
1050 This can be an ange-ftp or Tramp remote filename to download, or
1051 a local filename if you have full set of RFCs locally. See also
1052 `ffap-rfc-directories'."
1057 (defcustom ffap-rfc-directories nil
1058 "A list of directories to look for RFC files.
1059 If a given RFC isn't in these then `ffap-rfc-path' is offered."
1060 :type
'(repeat directory
)
1064 (defun ffap-rfc (name)
1065 (let ((num (match-string 1 name
)))
1066 (or (ffap-locate-file (format "rfc%s.txt" num
) t ffap-rfc-directories
)
1067 (format ffap-rfc-path num
))))
1070 ;;; At-Point Functions:
1072 (defvar ffap-string-at-point-mode-alist
1074 ;; The default, used when the `major-mode' is not found.
1075 ;; Slightly controversial decisions:
1076 ;; * strip trailing "@" and ":"
1077 ;; * no commas (good for latex)
1078 (file "--:\\\\${}+<>@-Z_[:alpha:]~*?" "<@" "@>;.,!:")
1079 ;; An url, or maybe a email/news message-id:
1080 (url "--:=&?$+@-Z_[:alpha:]~#,%;*()!'" "^[0-9a-zA-Z]" ":;.,!?")
1081 ;; Find a string that does *not* contain a colon:
1082 (nocolon "--9$+<>@-Z_[:alpha:]~" "<@" "@>;.,!?")
1084 (machine "-[:alnum:]." "" ".")
1085 ;; Mathematica paths: allow backquotes
1086 (math-mode ",-:$+<>@-Z_[:lower:]~`" "<" "@>;.,!?`:")
1087 ;; (La)TeX: don't allow braces
1088 (latex-mode "--:\\\\$+<>@-Z_[:alpha:]~*?" "<@" "@>;.,!:")
1089 (tex-mode "--:\\\\$+<>@-Z_[:alpha:]~*?" "<@" "@>;.,!:")
1091 "Alist of (MODE CHARS BEG END), where MODE is a symbol,
1092 possibly a major-mode name, or one of the symbols
1093 `file', `url', `machine', and `nocolon'.
1094 Function `ffap-string-at-point' uses the data fields as follows:
1095 1. find a maximal string of CHARS around point,
1096 2. strip BEG chars before point from the beginning,
1097 3. strip END chars after point from the end.
1098 The arguments CHARS, BEG and END are handled as described in
1099 `skip-chars-forward'.")
1101 (defvar ffap-string-at-point nil
1102 ;; Added at suggestion of RHOGEE (for ff-paths), 7/24/95.
1103 "Last string returned by the function `ffap-string-at-point'.")
1105 (defun ffap-string-at-point (&optional mode
)
1106 "Return a string of characters from around point.
1107 MODE (defaults to value of `major-mode') is a symbol used to look up
1108 string syntax parameters in `ffap-string-at-point-mode-alist'.
1109 If MODE is not found, we use `file' instead of MODE.
1110 If the region is active, return a string from the region.
1111 Sets the variable `ffap-string-at-point' and the variable
1112 `ffap-string-at-point-region'."
1115 (or (assq (or mode major-mode
) ffap-string-at-point-mode-alist
)
1116 (assq 'file ffap-string-at-point-mode-alist
))))
1118 (beg (if (use-region-p)
1121 (skip-chars-backward (car args
))
1122 (skip-chars-forward (nth 1 args
) pt
)
1124 (end (if (use-region-p)
1127 (skip-chars-forward (car args
))
1128 (skip-chars-backward (nth 2 args
) pt
)
1130 (setq ffap-string-at-point
1131 (buffer-substring-no-properties
1132 (setcar ffap-string-at-point-region beg
)
1133 (setcar (cdr ffap-string-at-point-region
) end
)))))
1135 (defun ffap-string-around ()
1136 ;; Sometimes useful to decide how to treat a string.
1137 "Return string of two chars around last result of function
1138 `ffap-string-at-point'.
1139 Assumes the buffer has not changed."
1143 (goto-char (car ffap-string-at-point-region
))
1144 (preceding-char)) ; maybe 0
1146 (goto-char (nth 1 ffap-string-at-point-region
))
1147 (following-char)) ; maybe 0
1150 (defun ffap-copy-string-as-kill (&optional mode
)
1151 ;; Requested by MCOOK. Useful?
1152 "Call function `ffap-string-at-point', and copy result to `kill-ring'."
1154 (let ((str (ffap-string-at-point mode
)))
1156 (message "No string found around point.")
1158 ;; Older: (apply 'copy-region-as-kill ffap-string-at-point-region)
1159 (message "Copied to kill ring: %s" str
))))
1162 (declare-function w3-view-this-url
"ext:w3" (&optional no-show
))
1164 (defun ffap-url-at-point ()
1165 "Return URL from around point if it exists, or nil.
1167 Sets the variable `ffap-string-at-point-region' to the bounds of URL, if any."
1168 (when ffap-url-regexp
1169 (or (and (eq major-mode
'w3-mode
) ; In a w3 buffer button?
1170 (w3-view-this-url t
))
1171 (let ((thing-at-point-beginning-of-url-regexp ffap-url-regexp
)
1172 (thing-at-point-default-mail-uri-scheme ffap-foo-at-bar-prefix
)
1174 (setq val
(thing-at-point-url-at-point ffap-lax-url
1176 (cons (region-beginning)
1179 (let ((bounds (thing-at-point-bounds-of-url-at-point
1181 (setq ffap-string-at-point-region
1182 (list (car bounds
) (cdr bounds
)))))
1185 (defvar ffap-gopher-regexp
1186 "^.*\\<\\(Type\\|Name\\|Path\\|Host\\|Port\\) *= *\\(.*\\) *$"
1187 "Regexp matching a line in a gopher bookmark (maybe indented).
1188 The two subexpressions are the KEY and VALUE.")
1190 (defun ffap-gopher-at-point ()
1191 "If point is inside a gopher bookmark block, return its URL.
1193 Sets the variable `ffap-string-at-point-region' to the bounds of URL, if any."
1194 ;; `gopher-parse-bookmark' from gopher.el is not so robust
1197 (if (looking-at ffap-gopher-regexp
)
1199 (while (and (looking-at ffap-gopher-regexp
) (not (bobp)))
1201 (or (looking-at ffap-gopher-regexp
) (forward-line 1))
1202 (setq ffap-string-at-point-region
(list (point) (point)))
1203 (let ((type "1") path host
(port "70"))
1204 (while (looking-at ffap-gopher-regexp
)
1207 (buffer-substring (match-beginning 1)
1209 (val (buffer-substring (match-beginning 2)
1213 (setcdr ffap-string-at-point-region
(list (point)))
1214 (if (and path
(string-match "^ftp:.*@" path
))
1216 (substring path
4 (1- (match-end 0)))
1217 (substring path
(match-end 0)))
1218 (and (= (length type
) 1)
1219 host
;; (ffap-machine-p host)
1220 (concat "gopher://" host
1221 (if (equal port
"70") "" (concat ":" port
))
1222 "/" type path
))))))))
1224 (defvar ffap-ftp-sans-slash-regexp
1227 ;; Note: by now, we know it is not an url.
1228 ;; Icky regexp avoids: default: 123: foo::bar cs:pub
1229 ;; It does match on: mic@cs: cs:/pub mathcs.emory.edu: (point at end)
1230 "\\`\\([^:@]+@[^:@]+:\\|[^@.:]+\\.[^@:]+:\\|[^:]+:[~/]\\)\\([^:]\\|\\'\\)")
1231 "Strings matching this are coerced to FTP file names by ffap.
1232 That is, ffap just prepends \"/\". Set to nil to disable.")
1234 (defun ffap-file-at-point ()
1235 "Return filename from around point if it exists, or nil.
1236 Existence test is skipped for names that look remote.
1237 If the filename is not obvious, it also tries `ffap-alist',
1238 which may actually result in an URL rather than a filename."
1239 ;; Note: this function does not need to look for url's, just
1240 ;; filenames. On the other hand, it is responsible for converting
1241 ;; a pseudo-url "site.com://dir" to an ftp file name
1242 (let* ((case-fold-search t
) ; url prefixes are case-insensitive
1244 (string (ffap-string-at-point)) ; uses mode alist
1246 (or (condition-case nil
1247 (and (not (string-match "//" string
)) ; foo.com://bar
1248 (substitute-in-file-name string
))
1251 (abs (file-name-absolute-p name
))
1252 (default-directory default-directory
)
1256 ;; Immediate rejects (/ and // and /* are too common in C/C++):
1257 ((member name
'("" "/" "//" "/*" ".")) nil
)
1258 ;; Immediately test local filenames. If default-directory is
1259 ;; remote, you probably already have a connection.
1260 ((and (not abs
) (ffap-file-exists-string name
)))
1261 ;; Try stripping off line numbers; good for compilation/grep output.
1262 ((and (not abs
) (string-match ":[0-9]" name
)
1263 (ffap-file-exists-string (substring name
0 (match-beginning 0)))))
1264 ;; Try stripping off prominent (non-root - #) shell prompts
1265 ;; if the ffap-shell-prompt-regexp is non-nil.
1266 ((and ffap-shell-prompt-regexp
1267 (not abs
) (string-match ffap-shell-prompt-regexp name
)
1268 (ffap-file-exists-string (substring name
(match-end 0)))))
1269 ;; Accept remote names without actual checking (too slow):
1270 ((and abs
(ffap-file-remote-p name
)))
1271 ;; Ok, not remote, try the existence test even if it is absolute:
1272 ((and abs
(ffap-file-exists-string name
)))
1273 ;; Try stripping off line numbers.
1274 ((and abs
(string-match ":[0-9]" name
)
1275 (ffap-file-exists-string (substring name
0 (match-beginning 0)))))
1276 ;; If it contains a colon, get rid of it (and return if exists)
1277 ((and (string-match path-separator name
)
1278 (setq name
(ffap-string-at-point 'nocolon
))
1279 (ffap-file-exists-string name
)))
1280 ;; File does not exist, try the alist:
1281 ((let ((alist ffap-alist
) tem try case-fold-search
)
1282 (while (and alist
(not try
))
1283 (setq tem
(car alist
) alist
(cdr alist
))
1284 (if (or (eq major-mode
(car tem
))
1285 (and (stringp (car tem
))
1286 (string-match (car tem
) name
)))
1289 (funcall (cdr tem
) name
)
1292 (ffap-url-p try
) ; not a file!
1293 (ffap-file-remote-p try
)
1294 (ffap-file-exists-string try
))))))
1296 ;; Try adding a leading "/" (common omission in ftp file names).
1297 ;; Note that this uses oname, which still has any colon part.
1298 ;; This should have a lower priority than the alist stuff,
1299 ;; else it matches things like "ffap.el:1234:56:Warning".
1301 ffap-ftp-sans-slash-regexp
1302 (string-match ffap-ftp-sans-slash-regexp oname
)
1303 (ffap-file-remote-p (concat "/" oname
))))
1304 ;; Alist failed? Try to guess an active remote connection
1305 ;; from buffer variables, and try once more, both as an
1306 ;; absolute and relative file name on that remote host.
1307 ((let* (ffap-rfs-regexp ; suppress
1310 ((ffap-file-remote-p default-directory
))
1311 ((and (eq major-mode
'internal-ange-ftp-mode
)
1312 (string-match "^\\*ftp \\(.*\\)@\\(.*\\)\\*$"
1314 (concat "/" (substring (buffer-name) 5 -
1) ":"))
1315 ;; This is too often a bad idea:
1316 ;;((and (eq major-mode 'w3-mode)
1317 ;; (stringp url-current-server))
1318 ;; (host-to-ange-path url-current-server))
1322 (and (string-match "\\`\\(/?~?ftp\\)/" name
)
1323 (ffap-file-exists-string
1324 (ffap-replace-file-component
1325 remote-dir
(substring name
(match-end 1)))))
1326 (ffap-file-exists-string
1327 (ffap-replace-file-component remote-dir name
))))))
1328 ((and ffap-dired-wildcards
1329 (string-match ffap-dired-wildcards name
)
1331 (ffap-file-exists-string (file-name-directory
1332 (directory-file-name name
)))
1334 ;; Try all parent directories by deleting the trailing directory
1335 ;; name until existing directory is found or name stops changing
1338 (not (ffap-file-exists-string dir
))
1339 (not (equal dir
(setq dir
(file-name-directory
1340 (directory-file-name dir
)))))))
1341 (and (not (string= dir
"/"))
1342 (ffap-file-exists-string dir
))))
1344 (set-match-data data
))))
1346 ;;; Prompting (`ffap-read-file-or-url'):
1348 ;; We want to complete filenames as in read-file-name, but also url's
1349 ;; which read-file-name-internal would truncate at the "//" string.
1350 ;; The solution here is to replace read-file-name-internal with
1351 ;; `ffap-read-file-or-url-internal', which checks the minibuffer
1352 ;; contents before attempting to complete filenames.
1354 (defun ffap-read-file-or-url (prompt guess
)
1355 "Read file or URL from minibuffer, with PROMPT and initial GUESS."
1356 (or guess
(setq guess default-directory
))
1358 ;; Tricky: guess may have or be a local directory, like "w3/w3.elc"
1359 ;; or "w3/" or "../el/ffap.el" or "../../../"
1360 (unless (ffap-url-p guess
)
1361 (unless (ffap-file-remote-p guess
)
1363 (abbreviate-file-name (expand-file-name guess
))))
1364 (setq dir
(file-name-directory guess
)))
1365 (let ((minibuffer-completing-file-name t
)
1366 (completion-ignore-case read-file-name-completion-ignore-case
)
1367 (fnh-elem (cons ffap-url-regexp
'url-file-handler
)))
1368 ;; Explain to `rfn-eshadow' that we can use URLs here.
1369 (push fnh-elem file-name-handler-alist
)
1372 (let ((default-directory (if dir
(expand-file-name dir
)
1373 default-directory
)))
1376 'ffap-read-file-or-url-internal
1379 (if dir
(cons guess
(length dir
)) guess
)
1381 (and buffer-file-name
1382 (abbreviate-file-name buffer-file-name
)))))
1383 ;; Remove the special handler manually. We used to just let-bind
1384 ;; file-name-handler-alist to preserve its value, but that caused
1385 ;; other modifications to be lost (e.g. when Tramp gets loaded
1386 ;; during the completing-read call).
1387 (setq file-name-handler-alist
(delq fnh-elem file-name-handler-alist
))))
1388 (or (ffap-url-p guess
)
1389 (substitute-in-file-name guess
))))
1391 (defun ffap-read-url-internal (string pred action
)
1392 "Complete URLs from history, treating given string as valid."
1393 (let ((hist (ffap-symbol-value 'url-global-history-hash-table
)))
1396 (or (try-completion string hist pred
) string
))
1398 (or (all-completions string hist pred
) (list string
)))
1399 ;; action == lambda, documented where? Tests whether string is a
1400 ;; valid "match". Let us always say yes.
1403 (defun ffap-read-file-or-url-internal (string pred action
)
1404 (let ((url (ffap-url-p string
)))
1406 (ffap-read-url-internal url pred action
)
1407 (read-file-name-internal (or string default-directory
) pred action
))))
1409 ;; The rest of this page is just to work with package complete.el.
1410 ;; This code assumes that you load ffap.el after complete.el.
1412 ;; We must inform complete about whether our completion function
1413 ;; will do filename style completion.
1416 ;;; Highlighting (`ffap-highlight'):
1418 (defvar ffap-highlight t
1419 "If non-nil, ffap highlights the current buffer substring.")
1422 '((t :inherit highlight
))
1423 "Face used to highlight the current buffer substring."
1427 (defvar ffap-highlight-overlay nil
1428 "Overlay used by function `ffap-highlight'.")
1430 (defun ffap-highlight (&optional remove
)
1431 "If `ffap-highlight' is set, highlight the guess in this buffer.
1432 That is, the last buffer substring found by `ffap-string-at-point'.
1433 Optional argument REMOVE means to remove any such highlighting.
1434 Uses the face `ffap' if it is defined, or else `highlight'."
1437 (and ffap-highlight-overlay
1438 (delete-overlay ffap-highlight-overlay
))
1440 ((not ffap-highlight
) nil
)
1441 (ffap-highlight-overlay
1443 ffap-highlight-overlay
1444 (car ffap-string-at-point-region
)
1445 (nth 1 ffap-string-at-point-region
)
1448 (setq ffap-highlight-overlay
1449 (apply 'make-overlay ffap-string-at-point-region
))
1450 (overlay-put ffap-highlight-overlay
'face
'ffap
))))
1453 ;;; Main Entrance (`find-file-at-point' == `ffap'):
1455 (defun ffap-guesser ()
1456 "Return file or URL or nil, guessed from text around point."
1457 (or (and ffap-url-regexp
1458 (ffap-fixup-url (or (ffap-url-at-point)
1459 (ffap-gopher-at-point))))
1460 (ffap-file-at-point) ; may yield url!
1461 (ffap-fixup-machine (ffap-machine-at-point))))
1463 (defun ffap-prompter (&optional guess
)
1464 ;; Does guess and prompt step for find-file-at-point.
1465 ;; Extra complication for the temporary highlighting.
1467 ;; This catch will let ffap-alist entries do their own prompting
1468 ;; and then maybe skip over this prompt (ff-paths, for example).
1469 (catch 'ffap-prompter
1470 (ffap-read-file-or-url
1471 (if ffap-url-regexp
"Find file or URL: " "Find file: ")
1473 (let ((mark-active nil
))
1474 ;; Don't use the region here, since it can be something
1475 ;; completely unwieldy. If the user wants that, she could
1476 ;; use M-w before and then C-y. --Stef
1477 (setq guess
(or guess
(ffap-guesser)))) ; using ffap-alist here
1478 (and guess
(ffap-highlight))
1480 (ffap-highlight t
)))
1483 (defun find-file-at-point (&optional filename
)
1484 "Find FILENAME, guessing a default from text around point.
1485 If `ffap-url-regexp' is not nil, the FILENAME may also be an URL.
1486 With a prefix, this command behaves exactly like `ffap-file-finder'.
1487 If `ffap-require-prefix' is set, the prefix meaning is reversed.
1488 See also the variables `ffap-dired-wildcards', `ffap-newfile-prompt',
1489 and the functions `ffap-file-at-point' and `ffap-url-at-point'."
1491 (if (and (called-interactively-p 'interactive
)
1492 (if ffap-require-prefix
(not current-prefix-arg
)
1493 current-prefix-arg
))
1494 ;; Do exactly the ffap-file-finder command, even the prompting:
1495 (let (current-prefix-arg) ; we already interpreted it
1496 (call-interactively ffap-file-finder
))
1497 (or filename
(setq filename
(ffap-prompter)))
1498 (let ((url (ffap-url-p filename
)))
1501 (let (current-prefix-arg)
1502 (funcall ffap-url-fetcher url
)))
1503 ((and ffap-pass-wildcards-to-dired
1504 ffap-dired-wildcards
1505 (string-match ffap-dired-wildcards filename
))
1506 (funcall ffap-directory-finder filename
))
1507 ((and ffap-dired-wildcards
1508 (string-match ffap-dired-wildcards filename
)
1510 ;; Check if it's find-file that supports wildcards arg
1511 (memq ffap-file-finder
'(find-file find-alternate-file
)))
1512 (funcall ffap-file-finder
(expand-file-name filename
) t
))
1513 ((or (not ffap-newfile-prompt
)
1514 (file-exists-p filename
)
1515 (y-or-n-p "File does not exist, create buffer? "))
1516 (funcall ffap-file-finder
1517 ;; expand-file-name fixes "~/~/.emacs" bug sent by CHUCKR.
1518 (expand-file-name filename
)))
1519 ;; User does not want to find a non-existent file:
1520 ((signal 'file-error
(list "Opening file buffer"
1521 "No such file or directory"
1524 ;; Shortcut: allow {M-x ffap} rather than {M-x find-file-at-point}.
1526 (defalias 'ffap
'find-file-at-point
)
1529 ;;; Menu support (`ffap-menu'):
1531 (defcustom ffap-menu-regexp nil
1532 "If non-nil, regexp overriding `ffap-next-regexp' in `ffap-menu'.
1533 Make this more restrictive for faster menu building.
1534 For example, try \":/\" for URL (and some FTP) references."
1535 :type
'(choice (const nil
) regexp
)
1538 (defvar ffap-menu-alist nil
1539 "Buffer local cache of menu presented by `ffap-menu'.")
1540 (make-variable-buffer-local 'ffap-menu-alist
)
1542 (defvar ffap-menu-text-plist
1544 ((display-mouse-p) '(face bold mouse-face highlight
)) ; keymap <mousy-map>
1546 "Text properties applied to strings found by `ffap-menu-rescan'.
1547 These properties may be used to fontify the menu references.")
1550 (defun ffap-menu (&optional rescan
)
1551 "Put up a menu of files and URLs mentioned in this buffer.
1552 Then set mark, jump to choice, and try to fetch it. The menu is
1553 cached in `ffap-menu-alist', and rebuilt by `ffap-menu-rescan'.
1554 The optional RESCAN argument (a prefix, interactively) forces
1555 a rebuild. Searches with `ffap-menu-regexp'."
1557 ;; (require 'imenu) -- no longer used, but roughly emulated
1558 (if (or (not ffap-menu-alist
) rescan
1559 ;; or if the first entry is wrong:
1560 (and ffap-menu-alist
1561 (let ((first (car ffap-menu-alist
)))
1563 (goto-char (cdr first
))
1564 (not (equal (car first
) (ffap-guesser)))))))
1568 (if ffap-url-regexp
"Find file or URL" "Find file")
1569 (cons (cons "*Rescan Buffer*" -
1) ffap-menu-alist
)
1572 (defun ffap-menu-cont (choice) ; continuation of ffap-menu
1573 (if (< (cdr choice
) 0)
1574 (ffap-menu t
) ; *Rescan*
1576 (goto-char (cdr choice
))
1577 ;; Momentary highlight:
1580 (and ffap-highlight
(ffap-guesser) (ffap-highlight))
1581 (sit-for 0) ; display
1582 (find-file-at-point (car choice
)))
1583 (ffap-highlight t
))))
1585 (defun ffap-menu-ask (title alist cont
)
1586 "Prompt from a menu of choices, and then apply some action.
1587 Arguments are TITLE, ALIST, and CONT (a continuation function).
1588 This uses either a menu or the minibuffer depending on invocation.
1589 The TITLE string is used as either the prompt or menu title.
1590 Each ALIST entry looks like (STRING . DATA) and defines one choice.
1591 Function CONT is applied to the entry chosen by the user."
1592 ;; Note: this function is used with a different continuation
1593 ;; by the ffap-url add-on package.
1594 ;; Could try rewriting to use easymenu.el or lmenu.el.
1598 ((and (fboundp 'x-popup-menu
) (ffap-mouse-event))
1602 (list "" (cons title
1603 (mapcar (lambda (i) (cons (car i
) i
))
1605 ;; minibuffer with completion buffer:
1607 (let ((minibuffer-setup-hook 'minibuffer-completion-help
))
1608 ;; Bug: prompting may assume unique strings, no "".
1611 (format "%s (default %s): " title
(car (car alist
)))
1613 ;; (cons (car (car alist)) 0)
1615 (sit-for 0) ; redraw original screen
1616 ;; Convert string to its entry, or else the default:
1617 (setq choice
(or (assoc choice alist
) (car alist
)))))
1619 (funcall cont choice
)
1620 (message "No choice made!") ; possible with menus
1623 (defun ffap-menu-rescan ()
1624 "Search buffer for `ffap-menu-regexp' to build `ffap-menu-alist'.
1625 Applies `ffap-menu-text-plist' text properties at all matches."
1627 (let ((ffap-next-regexp (or ffap-menu-regexp ffap-next-regexp
))
1628 (range (- (point-max) (point-min)))
1629 (mod (buffer-modified-p)) ; was buffer modified?
1630 ;; inhibit-read-only works on read-only text properties
1631 ;; as well as read-only buffers.
1632 (inhibit-read-only t
) ; to set text-properties
1634 ;; Avoid repeated searches of the *mode-alist:
1635 (major-mode (if (assq major-mode ffap-string-at-point-mode-alist
)
1638 (setq ffap-menu-alist nil
)
1641 (goto-char (point-min))
1642 (while (setq item
(ffap-next-guess))
1643 (setq ffap-menu-alist
(cons (cons item
(point)) ffap-menu-alist
))
1644 (add-text-properties (car ffap-string-at-point-region
) (point)
1645 ffap-menu-text-plist
)
1646 (message "Scanning...%2d%% <%s>"
1647 (floor (* 100.0 (- (point) (point-min))) range
) item
)))
1648 (or mod
(restore-buffer-modified-p nil
))))
1649 (message "Scanning...done")
1650 ;; Remove duplicates.
1651 (setq ffap-menu-alist
; sort by item
1652 (sort ffap-menu-alist
1654 (lambda (a b
) (string-lessp (car a
) (car b
))))))
1655 (let ((ptr ffap-menu-alist
)) ; remove duplicates
1657 (if (equal (car (car ptr
)) (car (car (cdr ptr
))))
1658 (setcdr ptr
(cdr (cdr ptr
)))
1659 (setq ptr
(cdr ptr
)))))
1660 (setq ffap-menu-alist
; sort by position
1661 (sort ffap-menu-alist
1663 (lambda (a b
) (< (cdr a
) (cdr b
)))))))
1666 ;;; Mouse Support (`ffap-at-mouse'):
1668 ;; See the suggested binding in ffap-bindings (near eof).
1670 (defvar ffap-at-mouse-fallback nil
; ffap-menu? too time-consuming
1671 "Command invoked by `ffap-at-mouse' if nothing found at click, or nil.
1672 Ignored when `ffap-at-mouse' is called programmatically.")
1673 (put 'ffap-at-mouse-fallback
'risky-local-variable t
)
1676 (defun ffap-at-mouse (e)
1677 "Find file or URL guessed from text around mouse click.
1678 Interactively, calls `ffap-at-mouse-fallback' if no guess is found.
1680 * if a guess string is found, return it (after finding it)
1681 * if the fallback is called, return whatever it returns
1685 ;; Maybe less surprising without the save-excursion?
1688 ;; Would prefer to do nothing unless click was *on* text. How
1689 ;; to tell that the click was beyond the end of current line?
1693 (set-buffer (ffap-event-buffer e
))
1697 (sit-for 0) ; display
1698 (message "Finding `%s'" guess
)
1699 (find-file-at-point guess
)
1700 guess
) ; success: return non-nil
1701 (ffap-highlight t
)))
1702 ((called-interactively-p 'interactive
)
1703 (if ffap-at-mouse-fallback
1704 (call-interactively ffap-at-mouse-fallback
)
1705 (message "No file or URL found at mouse click.")
1706 nil
)) ; no fallback, return nil
1707 ;; failure: return nil
1711 ;;; ffap-other-*, ffap-read-only-*, ffap-alternate-* commands:
1713 ;; There could be a real `ffap-noselect' function, but we would need
1714 ;; at least two new user variables, and there is no w3-fetch-noselect.
1715 ;; So instead, we just fake it with a slow save-window-excursion.
1717 (defun ffap-other-window ()
1718 "Like `ffap', but put buffer in another window.
1719 Only intended for interactive use."
1722 (switch-to-buffer-other-window
1723 (save-window-excursion
1724 (setq value
(call-interactively 'ffap
))
1725 (unless (or (bufferp value
) (bufferp (car-safe value
)))
1726 (setq value
(current-buffer)))
1730 (defun ffap-other-frame ()
1731 "Like `ffap', but put buffer in another frame.
1732 Only intended for interactive use."
1734 ;; Extra code works around dedicated windows (noted by JENS, 7/96):
1735 (let* ((win (selected-window))
1736 (wdp (window-dedicated-p win
))
1740 (set-window-dedicated-p win nil
)
1741 (switch-to-buffer-other-frame
1742 (save-window-excursion
1743 (setq value
(call-interactively 'ffap
))
1744 (unless (or (bufferp value
) (bufferp (car-safe value
)))
1745 (setq value
(current-buffer)))
1747 (set-window-dedicated-p win wdp
))
1750 (defun ffap--toggle-read-only (buffer-or-list)
1751 (dolist (buffer (if (listp buffer-or-list
)
1753 (list buffer-or-list
)))
1754 (with-current-buffer buffer
1755 (read-only-mode 1))))
1757 (defun ffap-read-only ()
1758 "Like `ffap', but mark buffer as read-only.
1759 Only intended for interactive use."
1761 (let ((value (call-interactively 'ffap
)))
1762 (unless (or (bufferp value
) (bufferp (car-safe value
)))
1763 (setq value
(current-buffer)))
1764 (ffap--toggle-read-only value
)
1767 (defun ffap-read-only-other-window ()
1768 "Like `ffap', but put buffer in another window and mark as read-only.
1769 Only intended for interactive use."
1771 (let ((value (ffap-other-window)))
1772 (ffap--toggle-read-only value
)
1775 (defun ffap-read-only-other-frame ()
1776 "Like `ffap', but put buffer in another frame and mark as read-only.
1777 Only intended for interactive use."
1779 (let ((value (ffap-other-frame)))
1780 (ffap--toggle-read-only value
)
1783 (defun ffap-alternate-file ()
1784 "Like `ffap' and `find-alternate-file'.
1785 Only intended for interactive use."
1787 (let ((ffap-file-finder 'find-alternate-file
))
1788 (call-interactively 'ffap
)))
1790 (defun ffap-alternate-file-other-window ()
1791 "Like `ffap' and `find-alternate-file-other-window'.
1792 Only intended for interactive use."
1794 (let ((ffap-file-finder 'find-alternate-file-other-window
))
1795 (call-interactively 'ffap
)))
1797 (defun ffap-literally ()
1798 "Like `ffap' and command `find-file-literally'.
1799 Only intended for interactive use."
1801 (let ((ffap-file-finder 'find-file-literally
))
1802 (call-interactively 'ffap
)))
1804 (defalias 'find-file-literally-at-point
'ffap-literally
)
1809 (define-obsolete-function-alias 'ffap-bug
'report-emacs-bug
"23.1")
1810 (define-obsolete-function-alias 'ffap-submit-bug
'report-emacs-bug
"23.1")
1813 ;;; Hooks for Gnus, VM, Rmail:
1815 ;; If you do not like these bindings, write versions with whatever
1816 ;; bindings you would prefer.
1818 (defun ffap-ro-mode-hook ()
1819 "Bind `ffap-next' and `ffap-menu' to M-l and M-m, resp."
1820 (local-set-key "\M-l" 'ffap-next
)
1821 (local-set-key "\M-m" 'ffap-menu
))
1823 (defun ffap-gnus-hook ()
1824 "Bind `ffap-gnus-next' and `ffap-gnus-menu' to M-l and M-m, resp."
1826 (setq-local thing-at-point-default-mail-uri-scheme
"news")
1827 ;; Note "l", "L", "m", "M" are taken:
1828 (local-set-key "\M-l" 'ffap-gnus-next
)
1829 (local-set-key "\M-m" 'ffap-gnus-menu
))
1831 (defvar gnus-summary-buffer
)
1832 (defvar gnus-article-buffer
)
1834 ;; This code is called from gnus.
1835 (declare-function gnus-summary-select-article
"gnus-sum"
1836 (&optional all-headers force pseudo article
))
1838 (declare-function gnus-configure-windows
"gnus-win"
1839 (setting &optional force
))
1841 (defun ffap-gnus-wrapper (form) ; used by both commands below
1842 (and (eq (current-buffer) (get-buffer gnus-summary-buffer
))
1843 (gnus-summary-select-article)) ; get article of current line
1844 ;; Preserve selected buffer, but do not do save-window-excursion,
1845 ;; since we want to see any window created by the form. Temporarily
1846 ;; select the article buffer, so we can see any point movement.
1847 (let ((sb (window-buffer)))
1848 (gnus-configure-windows 'article
)
1849 (pop-to-buffer gnus-article-buffer
)
1851 ;; Skip headers for ffap-gnus-next (which will wrap around)
1852 (if (eq (point) (point-min)) (search-forward "\n\n" nil t
))
1855 (pop-to-buffer sb
))))
1857 (defun ffap-gnus-next ()
1858 "Run `ffap-next' in the gnus article buffer."
1859 (interactive) (ffap-gnus-wrapper '(ffap-next nil t
)))
1861 (defun ffap-gnus-menu ()
1862 "Run `ffap-menu' in the gnus article buffer."
1863 (interactive) (ffap-gnus-wrapper '(ffap-menu)))
1868 (defun dired-at-point (&optional filename
)
1869 "Start Dired, defaulting to file at point. See `ffap'.
1870 If `dired-at-point-require-prefix' is set, the prefix meaning is reversed."
1872 (if (and (called-interactively-p 'interactive
)
1873 (if dired-at-point-require-prefix
1874 (not current-prefix-arg
)
1875 current-prefix-arg
))
1876 (let (current-prefix-arg) ; already interpreted
1877 (call-interactively ffap-directory-finder
))
1878 (or filename
(setq filename
(dired-at-point-prompter)))
1879 (let ((url (ffap-url-p filename
)))
1882 (funcall ffap-url-fetcher url
))
1883 ((and ffap-dired-wildcards
1884 (string-match ffap-dired-wildcards filename
))
1885 (funcall ffap-directory-finder filename
))
1886 ((file-exists-p filename
)
1887 (if (file-directory-p filename
)
1888 (funcall ffap-directory-finder
1889 (expand-file-name filename
))
1890 (funcall ffap-directory-finder
1891 (concat (expand-file-name filename
) "*"))))
1892 ((and (file-writable-p
1893 (or (file-name-directory (directory-file-name filename
))
1895 (y-or-n-p "Directory does not exist, create it? "))
1896 (make-directory filename
)
1897 (funcall ffap-directory-finder filename
))
1898 ((error "No such file or directory `%s'" filename
))))))
1900 (defun dired-at-point-prompter (&optional guess
)
1901 ;; Does guess and prompt step for find-file-at-point.
1902 ;; Extra complication for the temporary highlighting.
1904 (ffap-read-file-or-url
1906 ((eq ffap-directory-finder
'list-directory
)
1907 "List directory (brief): ")
1908 (ffap-url-regexp "Dired file or URL: ")
1912 (let ((guess (or guess
(ffap-guesser))))
1915 ((ffap-url-p guess
))
1916 ((ffap-file-remote-p guess
)
1919 (setq guess
(abbreviate-file-name
1920 (expand-file-name guess
)))
1921 ;; Interpret local directory as a directory.
1922 (file-directory-p guess
))
1923 (file-name-as-directory guess
))
1924 ;; Get directory component from local files.
1925 ((file-regular-p guess
)
1926 (file-name-directory guess
))
1928 (and guess
(ffap-highlight))))
1929 (ffap-highlight t
)))
1931 ;;; ffap-dired-other-*, ffap-list-directory commands:
1933 (defun ffap-dired-other-window ()
1934 "Like `dired-at-point', but put buffer in another window.
1935 Only intended for interactive use."
1938 (switch-to-buffer-other-window
1939 (save-window-excursion
1940 (setq value
(call-interactively 'dired-at-point
))
1944 (defun ffap-dired-other-frame ()
1945 "Like `dired-at-point', but put buffer in another frame.
1946 Only intended for interactive use."
1948 ;; Extra code works around dedicated windows (noted by JENS, 7/96):
1949 (let* ((win (selected-window))
1950 (wdp (window-dedicated-p win
))
1954 (set-window-dedicated-p win nil
)
1955 (switch-to-buffer-other-frame
1956 (save-window-excursion
1957 (setq value
(call-interactively 'dired-at-point
))
1959 (set-window-dedicated-p win wdp
))
1962 (defun ffap-list-directory ()
1963 "Like `dired-at-point' and `list-directory'.
1964 Only intended for interactive use."
1966 (let ((ffap-directory-finder 'list-directory
))
1967 (call-interactively 'dired-at-point
)))
1970 ;;; Hooks to put in `file-name-at-point-functions':
1973 (defun ffap-guess-file-name-at-point ()
1974 "Try to get a file name at point.
1975 This hook is intended to be put in `file-name-at-point-functions'."
1976 ;; ffap-guesser can signal an error, and we don't want that when,
1977 ;; e.g., the user types M-n at the "C-x C-f" prompt.
1978 (let ((guess (ignore-errors (ffap-guesser))))
1979 (when (stringp guess
)
1980 (let ((url (ffap-url-p guess
)))
1983 (unless (ffap-file-remote-p guess
)
1985 (abbreviate-file-name (expand-file-name guess
))))
1986 (if (file-directory-p guess
)
1987 (file-name-as-directory guess
)
1990 ;;; Offer default global bindings (`ffap-bindings'):
1992 (defvar ffap-bindings
1993 '((global-set-key [S-mouse-3
] 'ffap-at-mouse
)
1994 (global-set-key [C-S-mouse-3
] 'ffap-menu
)
1996 (global-set-key "\C-x\C-f" 'find-file-at-point
)
1997 (global-set-key "\C-x\C-r" 'ffap-read-only
)
1998 (global-set-key "\C-x\C-v" 'ffap-alternate-file
)
2000 (global-set-key "\C-x4f" 'ffap-other-window
)
2001 (global-set-key "\C-x5f" 'ffap-other-frame
)
2002 (global-set-key "\C-x4r" 'ffap-read-only-other-window
)
2003 (global-set-key "\C-x5r" 'ffap-read-only-other-frame
)
2005 (global-set-key "\C-xd" 'dired-at-point
)
2006 (global-set-key "\C-x4d" 'ffap-dired-other-window
)
2007 (global-set-key "\C-x5d" 'ffap-dired-other-frame
)
2008 (global-set-key "\C-x\C-d" 'ffap-list-directory
)
2010 (add-hook 'gnus-summary-mode-hook
'ffap-gnus-hook
)
2011 (add-hook 'gnus-article-mode-hook
'ffap-gnus-hook
)
2012 (add-hook 'vm-mode-hook
'ffap-ro-mode-hook
)
2013 (add-hook 'rmail-mode-hook
'ffap-ro-mode-hook
))
2014 "List of binding forms evaluated by function `ffap-bindings'.
2015 A reasonable ffap installation needs just this one line:
2017 Of course if you do not like these bindings, just roll your own!")
2020 (defun ffap-bindings ()
2021 "Evaluate the forms in variable `ffap-bindings'."
2023 (eval (cons 'progn ffap-bindings
)))
2028 ;;; ffap.el ends here