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