ffap.el 72 KB

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