mirrored from git://git.sv.gnu.org/emacs.git
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ffap.el
2076 lines (1857 loc) · 76.9 KB
/
ffap.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; ffap.el --- find file (or url) at point
;; Copyright (C) 1995-1997, 2000-2019 Free Software Foundation, Inc.
;; Author: Michelangelo Grigni <mic@mathcs.emory.edu>
;; Maintainer: emacs-devel@gnu.org
;; Created: 29 Mar 1993
;; Keywords: files, hypermedia, matching, mouse, convenience
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Command find-file-at-point replaces find-file. With a prefix, it
;; behaves exactly like find-file. Without a prefix, it first tries
;; to guess a default file or URL from the text around the point
;; (`ffap-require-prefix' swaps these behaviors). This is useful for
;; following references in situations such as mail or news buffers,
;; README's, MANIFEST's, and so on. Submit bugs or suggestions with
;; M-x report-emacs-bug.
;;
;; For the default installation, add this line to your init file:
;;
;; (ffap-bindings) ; do default key bindings
;;
;; ffap-bindings makes the following global key bindings:
;;
;; C-x C-f find-file-at-point (abbreviated as ffap)
;; C-x C-r ffap-read-only
;; C-x C-v ffap-alternate-file
;;
;; C-x d dired-at-point
;; C-x C-d ffap-list-directory
;;
;; C-x 4 f ffap-other-window
;; C-x 4 r ffap-read-only-other-window
;; C-x 4 d ffap-dired-other-window
;;
;; C-x 5 f ffap-other-frame
;; C-x 5 r ffap-read-only-other-frame
;; C-x 5 d ffap-dired-other-frame
;;
;; S-mouse-3 ffap-at-mouse
;; C-S-mouse-3 ffap-menu
;;
;; ffap-bindings also adds hooks to make the following local bindings
;; in vm, gnus, and rmail:
;;
;; M-l ffap-next, or ffap-gnus-next in gnus (l == "link")
;; M-m ffap-menu, or ffap-gnus-menu in gnus (m == "menu")
;;
;; If you do not like these bindings, modify the variable
;; `ffap-bindings', or write your own.
;;
;; If you use ange-ftp, browse-url, complete, efs, or w3, it is best
;; to load or autoload them before ffap. If you use ff-paths, load it
;; afterwards. Try apropos {C-h a ffap RET} to get a list of the many
;; option variables. In particular, if ffap is slow, try these:
;;
;; (setq ffap-alist nil) ; faster, dumber prompting
;; (setq ffap-machine-p-known 'accept) ; no pinging
;; (setq ffap-url-regexp nil) ; disable URL features in ffap
;; (setq ffap-shell-prompt-regexp nil) ; disable shell prompt stripping
;; (setq ffap-gopher-regexp nil) ; disable gopher bookmark matching
;;
;; ffap uses `browse-url' (if found, else `w3-fetch') to fetch URL's.
;; For a hairier `ffap-url-fetcher', try ffap-url.el (same ftp site).
;; Also, you can add `ffap-menu-rescan' to various hooks to fontify
;; the file and URL references within a buffer.
;;; Change Log:
;;
;; The History and Contributors moved to ffap.LOG (same ftp site),
;; which also has some old examples and commentary from ffap 1.5.
;;; Todo list:
;; * let "/dir/file#key" jump to key (tag or regexp) in /dir/file
;; * find file of symbol if TAGS is loaded (like above)
;; * break long menus into multiple panes (like imenu?)
;; * notice node in "(dired)Virtual Dired" (quotes, parentheses, whitespace)
;; * notice "machine.dom blah blah blah dir/file" (how?)
;; * as w3 becomes standard, rewrite to rely more on its functions
;; * regexp options for ffap-string-at-point, like font-lock (MCOOK)
;; * v19: could replace `ffap-locate-file' with a quieter `locate-library'
;; * handle "$(VAR)" in Makefiles
;; * use the font-lock machinery
;;; Code:
(require 'url-parse)
(require 'thingatpt)
(define-obsolete-variable-alias 'ffap-version 'emacs-version "23.2")
(defgroup ffap nil
"Find file or URL at point."
;; Dead 2009/07/05.
;; :link '(url-link :tag "URL" "ftp://ftp.mathcs.emory.edu/pub/mic/emacs/")
:group 'matching
:group 'convenience)
;; The code is organized in pages, separated by formfeed characters.
;; See the next two pages for standard customization ideas.
;;; User Variables:
(defun ffap-symbol-value (sym &optional default)
"Return value of symbol SYM, if bound, or DEFAULT otherwise."
(if (boundp sym) (symbol-value sym) default))
(defcustom ffap-shell-prompt-regexp
;; This used to test for some shell prompts that don't have a space
;; after them. The common root shell prompt (#) is not listed since it
;; also doubles up as a valid URL character.
"[$%><]*"
"Paths matching this regexp are stripped off the shell prompt.
If nil, ffap doesn't do shell prompt stripping."
:type '(choice (const :tag "Disable" nil)
(const :tag "Standard" "[$%><]*")
regexp)
:group 'ffap)
(defcustom ffap-ftp-regexp "\\`/[^/:]+:"
"File names matching this regexp are treated as remote ffap.
If nil, ffap neither recognizes nor generates such names."
:type '(choice (const :tag "Disable" nil)
(const :tag "Standard" "\\`/[^/:]+:")
regexp)
:group 'ffap)
(defcustom ffap-url-unwrap-local t
"If non-nil, convert some URLs to local file names before prompting.
Only \"file:\" and \"ftp:\" URLs are converted, and only if they
do not specify a host, or the host is either \"localhost\" or
equal to `system-name'."
:type 'boolean
:group 'ffap)
(defcustom ffap-url-unwrap-remote '("ftp")
"If non-nil, convert URLs to remote file names before prompting.
If the value is a list of strings, that specifies a list of URL
schemes (e.g. \"ftp\"); in that case, only convert those URLs."
:type '(choice (repeat string) boolean)
:group 'ffap
:version "24.3")
(defcustom ffap-lax-url t
"If non-nil, allow lax URL matching.
The default non-nil value might produce false URLs in C++ code
with symbols like \"std::find\". On the other hand, setting
this to nil will disable recognition of URLs that are not
well-formed, such as \"user@host\" or \"<user@host>\"."
:type 'boolean
:group 'ffap
:version "25.2") ; nil -> t
(defcustom ffap-ftp-default-user "anonymous"
"User name in FTP file names generated by `ffap-host-to-path'.
Note this name may be omitted if it equals the default
\(either `efs-default-user' or `ange-ftp-default-user')."
:type 'string
:group 'ffap)
(defcustom ffap-rfs-regexp
;; Remote file access built into file system? HP rfa or Andrew afs:
"\\`/\\(afs\\|net\\)/."
;; afs only: (and (file-exists-p "/afs") "\\`/afs/.")
"Matching file names are treated as remote. Use nil to disable."
:type 'regexp
:group 'ffap)
(defvar ffap-url-regexp
(concat
"\\("
"news\\(post\\)?:\\|mailto:\\|file:" ; no host ok
"\\|"
"\\(ftp\\|https?\\|telnet\\|gopher\\|www\\|wais\\)://" ; needs host
"\\)")
"Regexp matching the beginning of a URI, for ffap.
If the value is nil, disable URL-matching features in ffap.")
(defcustom ffap-foo-at-bar-prefix "mailto"
"Presumed URL prefix type of strings like \"<foo.9z@bar>\".
Sensible values are nil, \"news\", or \"mailto\"."
:type '(choice (const "mailto")
(const "news")
(const :tag "Disable" nil)
;; string -- possible, but not really useful
)
:group 'ffap)
(defvar ffap-max-region-length 1024
"Maximum active region length.
When the region is active and larger than this value,
`ffap-string-at-point' returns an empty string.")
;;; Peanut Gallery (More User Variables):
;;
;; Users of ffap occasionally suggest new features. If I consider
;; those features interesting but not clear winners (a matter of
;; personal taste) I try to leave options to enable them. Read
;; through this section for features that you like, put an appropriate
;; enabler in your init file.
(defcustom ffap-dired-wildcards "[*?][^/]*\\'"
"A regexp matching filename wildcard characters, or nil.
If `find-file-at-point' gets a filename matching this pattern,
and `ffap-pass-wildcards-to-dired' is nil, it passes it on to
`find-file' with non-nil WILDCARDS argument, which expands
wildcards and visits multiple files. To visit a file whose name
contains wildcard characters you can suppress wildcard expansion
by setting `find-file-wildcards'. If `find-file-at-point' gets a
filename matching this pattern and `ffap-pass-wildcards-to-dired'
is non-nil, it passes it on to `dired'.
If `dired-at-point' gets a filename matching this pattern,
it passes it on to `dired'."
:type '(choice (const :tag "Disable" nil)
(const :tag "Enable" "[*?][^/]*\\'")
;; regexp -- probably not useful
)
:group 'ffap)
(defcustom ffap-pass-wildcards-to-dired nil
"If non-nil, pass filenames matching `ffap-dired-wildcards' to Dired."
:type 'boolean
:group 'ffap)
(defcustom ffap-newfile-prompt nil
;; Suggestion from RHOGEE, 11 Jul 1994. Disabled, I think this is
;; better handled by `find-file-not-found-functions'.
"Whether `find-file-at-point' prompts about a nonexistent file."
:type 'boolean
:group 'ffap)
(defcustom ffap-require-prefix nil
;; Suggestion from RHOGEE, 20 Oct 1994.
"If set, reverses the prefix argument to `find-file-at-point'.
This is nil so neophytes notice ffap. Experts may prefer to disable
ffap most of the time."
:type 'boolean
:group 'ffap)
(defcustom ffap-file-finder 'find-file
"The command called by `find-file-at-point' to find a file."
:type 'function
:group 'ffap
:risky t)
(defcustom ffap-directory-finder 'dired
"The command called by `dired-at-point' to find a directory."
:type 'function
:group 'ffap
:risky t)
(defcustom ffap-url-fetcher 'browse-url
"A function of one argument, called by ffap to fetch an URL.
For a fancy alternative, get `ffap-url.el'."
:type '(choice (const browse-url)
function)
:group 'ffap
:risky t)
(defcustom ffap-next-regexp
;; If you want ffap-next to find URL's only, try this:
;; (and ffap-url-regexp (string-match "\\\\`" ffap-url-regexp)
;; (concat "\\<" (substring ffap-url-regexp 2))))
;;
;; It pays to put a big fancy regexp here, since ffap-guesser is
;; much more time-consuming than regexp searching:
"[/:.~[:alpha:]]/\\|@[[:alpha:]][-[:alnum:]]*\\."
"Regular expression governing movements of `ffap-next'."
:type 'regexp
:group 'ffap)
(defcustom dired-at-point-require-prefix nil
"If non-nil, reverse the prefix argument to `dired-at-point'.
This is nil so neophytes notice ffap. Experts may prefer to
disable ffap most of the time."
:type 'boolean
:group 'ffap
:version "20.3")
;;; Compatibility:
;;
;; This version of ffap supports only the Emacs it is distributed in.
;; See the ftp site for a more general version. The following
;; functions are necessary "leftovers" from the more general version.
(defun ffap-mouse-event () ; current mouse event, or nil
(and (listp last-nonmenu-event) last-nonmenu-event))
(defun ffap-event-buffer (event)
(window-buffer (car (event-start event))))
;;; Find Next Thing in buffer (`ffap-next'):
;;
;; Original ffap-next-url (URL's only) from RPECK 30 Mar 1995. Since
;; then, broke it up into ffap-next-guess (noninteractive) and
;; ffap-next (a command). It now work on files as well as url's.
(defvar ffap-next-guess nil
"Last value returned by `ffap-next-guess'.")
(defvar ffap-string-at-point-region '(1 1)
"List (BEG END), last region returned by the function `ffap-string-at-point'.")
(defun ffap-next-guess (&optional back lim)
"Move point to next file or URL, and return it as a string.
If nothing is found, leave point at limit and return nil.
Optional BACK argument makes search backwards.
Optional LIM argument limits the search.
Only considers strings that match `ffap-next-regexp'."
(or lim (setq lim (if back (point-min) (point-max))))
(let (guess)
(while (not (or guess (eq (point) lim)))
(funcall (if back 're-search-backward 're-search-forward)
ffap-next-regexp lim 'move)
(setq guess (ffap-guesser)))
;; Go to end, so we do not get same guess twice:
(goto-char (nth (if back 0 1) ffap-string-at-point-region))
(setq ffap-next-guess guess)))
;;;###autoload
(defun ffap-next (&optional back wrap)
"Search buffer for next file or URL, and run ffap.
Optional argument BACK says to search backwards.
Optional argument WRAP says to try wrapping around if necessary.
Interactively: use a single prefix \\[universal-argument] to search backwards,
double prefix to wrap forward, triple to wrap backwards.
Actual search is done by the function `ffap-next-guess'."
(interactive
(cdr (assq (prefix-numeric-value current-prefix-arg)
'((1) (4 t) (16 nil t) (64 t t)))))
(let ((pt (point))
(guess (ffap-next-guess back)))
;; Try wraparound if necessary:
(and (not guess) wrap
(goto-char (if back (point-max) (point-min)))
(setq guess (ffap-next-guess back pt)))
(if guess
(progn
(sit-for 0) ; display point movement
(find-file-at-point (ffap-prompter guess)))
(goto-char pt) ; restore point
(message "No %sfiles or URL's found"
(if wrap "" "more ")))))
(defun ffap-next-url (&optional back wrap)
"Like `ffap-next', but search with `ffap-url-regexp'."
(interactive)
(let ((ffap-next-regexp ffap-url-regexp))
(if (called-interactively-p 'interactive)
(call-interactively 'ffap-next)
(ffap-next back wrap))))
;;; Machines (`ffap-machine-p'):
;; I cannot decide a "best" strategy here, so these are variables. In
;; particular, if `Pinging...' is broken or takes too long on your
;; machine, try setting these all to accept or reject.
(defcustom ffap-machine-p-local 'reject ; this happens often
"What `ffap-machine-p' does with hostnames that have no domain.
Value should be a symbol, one of `ping', `accept', and `reject'."
:type '(choice (const ping)
(const accept)
(const reject))
:group 'ffap)
(defcustom ffap-machine-p-known 'ping ; `accept' for higher speed
"What `ffap-machine-p' does with hostnames that have a known domain.
Value should be a symbol, one of `ping', `accept', and `reject'.
See `mail-extr.el' for the known domains."
:type '(choice (const ping)
(const accept)
(const reject))
:group 'ffap)
(defcustom ffap-machine-p-unknown 'reject
"What `ffap-machine-p' does with hostnames that have an unknown domain.
Value should be a symbol, one of `ping', `accept', and `reject'.
See `mail-extr.el' for the known domains."
:type '(choice (const ping)
(const accept)
(const reject))
:group 'ffap)
(defun ffap-what-domain (domain)
;; Like what-domain in mail-extr.el, returns string or nil.
(require 'mail-extr)
(let ((ob (or (ffap-symbol-value 'mail-extr-all-top-level-domains)
(ffap-symbol-value 'all-top-level-domains)))) ; XEmacs
(and ob (get (intern-soft (downcase domain) ob) 'domain-name))))
(defun ffap-machine-p (host &optional service quiet strategy)
"Decide whether HOST is the name of a real, reachable machine.
Depending on the domain (none, known, or unknown), follow the strategy
named by the variable `ffap-machine-p-local', `ffap-machine-p-known',
or `ffap-machine-p-unknown'. Pinging uses `open-network-stream'.
Optional SERVICE specifies the port used (default \"discard\").
Optional QUIET flag suppresses the \"Pinging...\" message.
Optional STRATEGY overrides the three variables above.
Returned values:
t means that HOST answered.
`accept' means the relevant variable told us to accept.
\"mesg\" means HOST exists, but does not respond for some reason."
;; Try some (Emory local):
;; (ffap-machine-p "ftp" nil nil 'ping)
;; (ffap-machine-p "nonesuch" nil nil 'ping)
;; (ffap-machine-p "ftp.mathcs.emory.edu" nil nil 'ping)
;; (ffap-machine-p "mathcs" 5678 nil 'ping)
;; (ffap-machine-p "foo.bonk" nil nil 'ping)
;; (ffap-machine-p "foo.bonk.com" nil nil 'ping)
(if (or (string-match "[^-[:alnum:].]" host) ; Invalid chars (?)
(not (string-match "[^0-9]" host))) ; 1: a number? 2: quick reject
nil
(let* ((domain
(and (string-match "\\.[^.]*$" host)
(downcase (substring host (1+ (match-beginning 0))))))
(what-domain (if domain (ffap-what-domain domain) "Local")))
(or strategy
(setq strategy
(cond ((not domain) ffap-machine-p-local)
((not what-domain) ffap-machine-p-unknown)
(t ffap-machine-p-known))))
(cond
((eq strategy 'accept) 'accept)
((eq strategy 'reject) nil)
((not (fboundp 'open-network-stream)) nil)
;; assume (eq strategy 'ping)
(t
(or quiet
(if (stringp what-domain)
(message "Pinging %s (%s)..." host what-domain)
(message "Pinging %s ..." host)))
(condition-case error
(progn
(delete-process
(open-network-stream
"ffap-machine-p" nil host (or service "discard")))
t)
(error
(let ((mesg (car (cdr error))))
(cond
;; v18:
((string-match "\\(^Unknown host\\|Name or service not known$\\)"
mesg) nil)
((string-match "not responding$" mesg) mesg)
;; v19:
;; (file-error "connection failed" "permission denied"
;; "nonesuch" "ffap-machine-p")
;; (file-error "connection failed" "host is unreachable"
;; "gopher.house.gov" "ffap-machine-p")
;; (file-error "connection failed" "address already in use"
;; "ftp.uu.net" "ffap-machine-p")
((equal mesg "connection failed")
(if (string= (downcase (nth 2 error)) "permission denied")
nil ; host does not exist
;; Other errors mean the host exists:
(nth 2 error)))
;; Could be "Unknown service":
(t (signal (car error) (cdr error))))))))))))
;;; Possibly Remote Resources:
(defun ffap-replace-file-component (fullname name)
"In remote FULLNAME, replace path with NAME. May return nil."
;; Use efs if loaded, but do not load it otherwise.
(if (fboundp 'efs-replace-path-component)
(funcall 'efs-replace-path-component fullname name)
(and (stringp fullname)
(stringp name)
(concat (file-remote-p fullname) name))))
;; (ffap-replace-file-component "/who@foo.com:/whatever" "/new")
(defun ffap-file-suffix (file)
"Return trailing `.foo' suffix of FILE, or nil if none."
(let ((pos (string-match "\\.[^./]*\\'" file)))
(and pos (substring file pos nil))))
(defvar ffap-compression-suffixes '(".gz" ".Z") ; .z is mostly dead
"List of suffixes tried by `ffap-file-exists-string'.")
(defun ffap-file-exists-string (file &optional nomodify)
;; Early jka-compr versions modified file-exists-p to return the
;; filename, maybe modified by adding a suffix like ".gz". That
;; broke the interface of file-exists-p, so it was later dropped.
;; Here we document and simulate the old behavior.
"Return FILE (maybe modified) if the file exists, else nil.
When using jka-compr (a.k.a. `auto-compression-mode'), the returned
name may have a suffix added from `ffap-compression-suffixes'.
The optional NOMODIFY argument suppresses the extra search."
(cond
((not file) nil) ; quietly reject nil
((file-exists-p file) file) ; try unmodified first
;; three reasons to suppress search:
(nomodify nil)
((not (rassq 'jka-compr-handler file-name-handler-alist)) nil)
((member (ffap-file-suffix file) ffap-compression-suffixes) nil)
(t ; ok, do the search
(let ((list ffap-compression-suffixes) try ret)
(while list
(if (file-exists-p (setq try (concat file (car list))))
(setq ret try list nil)
(setq list (cdr list))))
ret))))
(defun ffap-file-remote-p (filename)
"If FILENAME looks remote, return it (maybe slightly improved)."
;; (ffap-file-remote-p "/user@foo.bar.com:/pub")
;; (ffap-file-remote-p "/cssun.mathcs.emory.edu://dir")
;; (ffap-file-remote-p "/ffap.el:80")
(or (and ffap-ftp-regexp
(string-match ffap-ftp-regexp filename)
;; Convert "/host.com://dir" to "/host:/dir", to handle a dying
;; practice of advertising ftp files as "host.dom://filename".
(if (string-match "//" filename)
;; (replace-match "/" nil nil filename)
(concat (substring filename 0 (1+ (match-beginning 0)))
(substring filename (match-end 0)))
filename))
(and ffap-rfs-regexp
(string-match ffap-rfs-regexp filename)
filename)))
(defun ffap-machine-at-point ()
"Return machine name at point if it exists, or nil."
(let ((mach (ffap-string-at-point 'machine)))
(and (ffap-machine-p mach) mach)))
(defsubst ffap-host-to-filename (host)
"Convert HOST to something like \"/USER@HOST:\" or \"/HOST:\".
Looks at `ffap-ftp-default-user', returns \"\" for \"localhost\"."
(if (equal host "localhost")
""
(let ((user ffap-ftp-default-user))
;; Avoid including the user if it is same as default:
(if (or (equal user (ffap-symbol-value 'ange-ftp-default-user))
(equal user (ffap-symbol-value 'efs-default-user)))
(setq user nil))
(concat "/" user (and user "@") host ":"))))
(defun ffap-fixup-machine (mach)
;; Convert a hostname into an url, an ftp file name, or nil.
(cond
((not (and ffap-url-regexp (stringp mach))) nil)
;; gopher.well.com
((string-match "\\`gopher[-.]" mach) ; or "info"?
(concat "gopher://" mach "/"))
;; www.ncsa.uiuc.edu
((and (string-match "\\`w\\(ww\\|eb\\)[-.]" mach))
(concat "http://" mach "/"))
;; More cases? Maybe "telnet:" for archie?
(ffap-ftp-regexp (ffap-host-to-filename mach))
))
(defvaralias 'ffap-newsgroup-regexp 'thing-at-point-newsgroup-regexp)
(defvaralias 'ffap-newsgroup-heads 'thing-at-point-newsgroup-heads)
(defalias 'ffap-newsgroup-p 'thing-at-point-newsgroup-p)
(defun ffap-url-p (string)
"If STRING looks like an URL, return it (maybe improved), else nil."
(when (and (stringp string) ffap-url-regexp)
(let* ((case-fold-search t)
(match (string-match ffap-url-regexp string)))
(cond ((eq match 0) string)
(match (substring string match))))))
;; Broke these out of ffap-fixup-url, for use of ffap-url package.
(defun ffap-url-unwrap-local (url)
"Return URL as a local file name, or nil."
(let* ((obj (url-generic-parse-url url))
(host (url-host obj))
(filename (car (url-path-and-query obj))))
(when (and (member (url-type obj) '("ftp" "file"))
(member host `("" "localhost" ,(system-name))))
;; On Windows, "file:///C:/foo" should unwrap to "C:/foo"
(if (and (memq system-type '(ms-dos windows-nt cygwin))
(string-match "\\`/[a-zA-Z]:" filename))
(substring filename 1)
filename))))
(defun ffap-url-unwrap-remote (url)
"Return URL as a remote file name, or nil."
(let* ((obj (url-generic-parse-url url))
(scheme (url-type obj))
(valid-schemes (if (listp ffap-url-unwrap-remote)
ffap-url-unwrap-remote
'("ftp")))
(host (url-host obj))
(port (url-port-if-non-default obj))
(user (url-user obj))
(filename (car (url-path-and-query obj))))
(when (and (member scheme valid-schemes)
(string-match "\\`[a-zA-Z][-a-zA-Z0-9+.]*\\'" scheme)
(not (equal host "")))
(concat "/" scheme ":"
(if user (concat user "@"))
host
(if port (concat "#" (number-to-string port)))
":" filename))))
(defun ffap-fixup-url (url)
"Clean up URL and return it, maybe as a file name."
(cond
((not (stringp url)) nil)
((and ffap-url-unwrap-local (ffap-url-unwrap-local url)))
((and ffap-url-unwrap-remote (ffap-url-unwrap-remote url)))
(url)))
;;; File Name Handling:
;;
;; The upcoming ffap-alist actions need various utilities to prepare
;; and search directories. Too many features here.
;; (defun ffap-last (l) (while (cdr l) (setq l (cdr l))) l)
;; (defun ffap-splice (func inlist)
;; "Equivalent to (apply 'nconc (mapcar FUNC INLIST)), but less consing."
;; (let* ((head (cons 17 nil)) (last head))
;; (while inlist
;; (setcdr last (funcall func (car inlist)))
;; (setq last (ffap-last last) inlist (cdr inlist)))
;; (cdr head)))
(defun ffap-list-env (env &optional empty)
"Return a list of strings parsed from environment variable ENV.
Optional EMPTY is the default list if (getenv ENV) is undefined, and
also is substituted for the first empty-string component, if there is one.
Uses `path-separator' to separate the path into substrings."
;; We cannot use parse-colon-path (files.el), since it kills
;; "//" entries using file-name-as-directory.
;; Similar: dired-split, TeX-split-string, and RHOGEE's psg-list-env
;; in ff-paths and bib-cite. The EMPTY arg may help mimic kpathsea.
(if (or empty (getenv env)) ; should return something
(let ((start 0) match dir ret)
(setq env (concat (getenv env) path-separator))
(while (setq match (string-match path-separator env start))
(setq dir (substring env start match) start (1+ match))
;;(and (file-directory-p dir) (not (member dir ret)) ...)
(setq ret (cons dir ret)))
(setq ret (nreverse ret))
(and empty (setq match (member "" ret))
(progn ; allow string or list here
(setcdr match (append (cdr-safe empty) (cdr match)))
(setcar match (or (car-safe empty) empty))))
ret)))
(defun ffap-reduce-path (path)
"Remove duplicates and non-directories from PATH list."
(let (ret tem)
(while path
(setq tem path path (cdr path))
(if (equal (car tem) ".") (setcar tem ""))
(or (member (car tem) ret)
(not (file-directory-p (car tem)))
(progn (setcdr tem ret) (setq ret tem))))
(nreverse ret)))
(defun ffap-all-subdirs (dir &optional depth)
"Return list of all subdirectories under DIR, starting with itself.
Directories beginning with \".\" are ignored, and directory symlinks
are listed but never searched (to avoid loops).
Optional DEPTH limits search depth."
(and (file-exists-p dir)
(ffap-all-subdirs-loop (expand-file-name dir) (or depth -1))))
(defun ffap-all-subdirs-loop (dir depth) ; internal
(setq depth (1- depth))
(cons dir
(and (not (eq depth -1))
(apply 'nconc
(mapcar
(function
(lambda (d)
(cond
((not (file-directory-p d)) nil)
((file-symlink-p d) (list d))
(t (ffap-all-subdirs-loop d depth)))))
(directory-files dir t "\\`[^.]")
)))))
(defvar ffap-kpathsea-depth 1
"Bound on depth of subdirectory search in `ffap-kpathsea-expand-path'.
Set to 0 to avoid all searching, or nil for no limit.")
(defun ffap-kpathsea-expand-path (path)
"Replace each \"//\"-suffixed dir in PATH by a list of its subdirs.
The subdirs begin with the original directory, and the depth of the
search is bounded by `ffap-kpathsea-depth'. This is intended to mimic
kpathsea, a library used by some versions of TeX."
(apply 'nconc
(mapcar
(function
(lambda (dir)
(if (string-match "[^/]//\\'" dir)
(ffap-all-subdirs (substring dir 0 -2) ffap-kpathsea-depth)
(list dir))))
path)))
(defun ffap-locate-file (file nosuffix path)
;; The current version of locate-library could almost replace this,
;; except it does not let us override the suffix list. The
;; compression-suffixes search moved to ffap-file-exists-string.
"A generic path-searching function.
Returns the name of file in PATH, or nil.
Optional NOSUFFIX, if nil or t, is like the fourth argument
for `load': whether to try the suffixes (\".elc\" \".el\" \"\").
If a nonempty list, it is a list of suffixes to try instead.
PATH is a list of directories.
This uses `ffap-file-exists-string', which may try adding suffixes from
`ffap-compression-suffixes'."
(if (file-name-absolute-p file)
(setq path (list (file-name-directory file))
file (file-name-nondirectory file)))
(let ((dir-ok (equal "" (file-name-nondirectory file)))
(suffixes-to-try
(cond
((consp nosuffix) nosuffix)
(nosuffix '(""))
(t '(".elc" ".el" ""))))
suffixes try found)
(while path
(setq suffixes suffixes-to-try)
(while suffixes
(setq try (ffap-file-exists-string
(expand-file-name
(concat file (car suffixes)) (car path))))
(if (and try (or dir-ok (not (file-directory-p try))))
(setq found try suffixes nil path nil)
(setq suffixes (cdr suffixes))))
(setq path (cdr path)))
found))
;;; Action List (`ffap-alist'):
;;
;; These search actions depend on the major-mode or regexps matching
;; the current name. The little functions and their variables are
;; deferred to the next section, at some loss of "code locality". A
;; good example of featuritis. Trim this list for speed.
(defvar ffap-alist
'(
("" . ffap-completable) ; completion, slow on some systems
("\\.info\\'" . ffap-info) ; gzip.info
("\\`info/" . ffap-info-2) ; info/emacs
("\\`[-[:lower:]]+\\'" . ffap-info-3) ; (emacs)Top [only in the parentheses]
("\\.elc?\\'" . ffap-el) ; simple.el, simple.elc
(emacs-lisp-mode . ffap-el-mode) ; rmail, gnus, simple, custom
;; (lisp-interaction-mode . ffap-el-mode) ; maybe
(finder-mode . ffap-el-mode) ; type {C-h p} and try it
(help-mode . ffap-el-mode) ; maybe useful
(c++-mode . ffap-c++-mode) ; search ffap-c++-path
(cc-mode . ffap-c-mode) ; same
("\\.\\([chCH]\\|cc\\|hh\\)\\'" . ffap-c-mode) ; stdio.h
(fortran-mode . ffap-fortran-mode) ; FORTRAN requested by MDB
("\\.[fF]\\'" . ffap-fortran-mode)
(tex-mode . ffap-tex-mode) ; search ffap-tex-path
(latex-mode . ffap-latex-mode) ; similar
("\\.\\(tex\\|sty\\|doc\\|cls\\)\\'" . ffap-tex)
("\\.bib\\'" . ffap-bib) ; search ffap-bib-path
("\\`\\." . ffap-home) ; .emacs, .bashrc, .profile
("\\`~/" . ffap-lcd) ; |~/misc/ffap.el.Z|
;; This used to have a blank, but ffap-string-at-point doesn't
;; handle blanks.
;; https://lists.gnu.org/r/emacs-devel/2008-01/msg01058.html
("\\`[Rr][Ff][Cc][-#]?\\([0-9]+\\)" ; no $
. ffap-rfc) ; "100% RFC2100 compliant"
(dired-mode . ffap-dired) ; maybe in a subdirectory
)
"Alist of (KEY . FUNCTION) pairs parsed by `ffap-file-at-point'.
If string NAME at point (maybe \"\") is not a file or URL, these pairs
specify actions to try creating such a string. A pair matches if either
KEY is a symbol, and it equals `major-mode', or
KEY is a string, it should match NAME as a regexp.
On a match, (FUNCTION NAME) is called and should return a file, an
URL, or nil. If nil, search the alist for further matches.
While calling FUNCTION, the match data is set according to KEY if KEY
is a string, so that FUNCTION can use `match-string' and friends
to extract substrings.")
(put 'ffap-alist 'risky-local-variable t)
;; Example `ffap-alist' modifications:
;;
;; (setq ffap-alist ; remove a feature in `ffap-alist'
;; (delete (assoc 'c-mode ffap-alist) ffap-alist))
;;
;; (setq ffap-alist ; add something to `ffap-alist'
;; (cons
;; (cons "^YSN[0-9]+$"
;; (defun ffap-ysn (name)
;; (concat
;; "http://www.physics.uiuc.edu/"
;; "ysn/httpd/htdocs/ysnarchive/issuefiles/"
;; (substring name 3) ".html")))
;; ffap-alist))
;;; Action Definitions:
;;
;; Define various default members of `ffap-alist'.
(defun ffap-completable (name)
(let* ((dir (or (file-name-directory name) default-directory))
(cmp (file-name-completion (file-name-nondirectory name) dir)))
(and cmp (concat dir cmp))))
(defun ffap-home (name) (ffap-locate-file name t '("~")))
(defun ffap-info (name)
(ffap-locate-file
name '("" ".info")
(or (ffap-symbol-value 'Info-directory-list)
(ffap-symbol-value 'Info-default-directory-list)
)))
(defun ffap-info-2 (name) (ffap-info (substring name 5)))
(defun ffap-info-3 (name)
;; This ignores the node! "(emacs)Top" same as "(emacs)Intro"
(and (equal (ffap-string-around) "()") (ffap-info name)))
(defun ffap-el (name) (ffap-locate-file name t load-path))
(defun ffap-el-mode (name)
;; If name == "foo.el" we will skip it, since ffap-el already
;; searched for it once. (This assumes the default ffap-alist.)
(and (not (string-match "\\.el\\'" name))
(ffap-locate-file name '(".el") load-path)))
;; FIXME this duplicates the logic of Man-header-file-path.
;; There should be a single central variable or function for this.
;; See also (bug#10702):
;; cc-search-directories, semantic-c-dependency-system-include-path,
;; semantic-gcc-setup
(defvar ffap-c-path
(let ((arch (with-temp-buffer
(when (eq 0 (ignore-errors
(call-process "gcc" nil '(t nil) nil
"-print-multiarch")))
(goto-char (point-min))
(buffer-substring (point) (line-end-position)))))
(base '("/usr/include" "/usr/local/include")))
(if (zerop (length arch))
base
(append base (list (expand-file-name arch "/usr/include")))))
"List of directories to search for include files.")
(defun ffap-c-mode (name)
(ffap-locate-file name t ffap-c-path))
(defvar ffap-c++-path
(let ((c++-include-dir (with-temp-buffer
(when (eq 0 (ignore-errors
(call-process "g++" nil t nil "-v")))
(goto-char (point-min))
(if (re-search-forward "--with-gxx-include-dir=\
\\([^[:space:]]+\\)"
nil 'noerror)
(match-string 1)
(when (re-search-forward "gcc version \
\\([[:digit:]]+.[[:digit:]]+.[[:digit:]]+\\)"
nil 'noerror)
(expand-file-name (match-string 1)
"/usr/include/c++/")))))))
(if c++-include-dir
(cons c++-include-dir ffap-c-path)
ffap-c-path))
"List of directories to search for include files.")
(defun ffap-c++-mode (name)
(ffap-locate-file name t ffap-c++-path))
(defvar ffap-fortran-path '("../include" "/usr/include"))
(defun ffap-fortran-mode (name)
(ffap-locate-file name t ffap-fortran-path))
(defvar ffap-tex-path
t ; delayed initialization
"Path where `ffap-tex-mode' looks for TeX files.
If t, `ffap-tex-init' will initialize this when needed.")
(defvar ffap-latex-guess-rules '(("" . ".sty")
("" . ".cls")
("" . ".ltx")
("" . ".tex")
("" . "") ;; in some rare cases the
;; extension is already in
;; the buffer.
("beamertheme" . ".sty")
("beamercolortheme". ".sty")
("beamerfonttheme". ".sty")
("beamerinnertheme". ".sty")
("beameroutertheme". ".sty")
("" . ".ldf"))
"List of rules for guessing a filename.
Each rule is a cons (PREFIX . SUFFIX) used for guessing a
filename from the word at point by prepending PREFIX and
appending SUFFIX.")
(defun ffap-tex-init ()
;; Compute ffap-tex-path if it is now t.
(and (eq t ffap-tex-path)
;; this may be slow, so say something
(message "Initializing ffap-tex-path ...")
(setq ffap-tex-path
(ffap-reduce-path
(cons
"."
(ffap-kpathsea-expand-path
(append
(ffap-list-env "TEXINPUTS")
;; (ffap-list-env "BIBINPUTS")
(ffap-symbol-value
'TeX-macro-global ; AUCTeX
'("/usr/local/lib/tex/macros"
"/usr/local/lib/tex/inputs")))))))))
(defun ffap-tex-mode (name)
(ffap-tex-init)
(ffap-locate-file name '(".tex" "") ffap-tex-path))
(defun ffap-latex-mode (name)
"`ffap' function suitable for latex buffers.
This uses the program kpsewhich if available. In this case, the
variable `ffap-latex-guess-rules' is used for building a filename
out of NAME."
(cond ((file-exists-p name)
name)
((not (executable-find "kpsewhich"))
(ffap-tex-init)
(ffap-locate-file name '(".cls" ".sty" ".tex" "") ffap-tex-path))
(t
(let ((curbuf (current-buffer))
(guess-rules ffap-latex-guess-rules)
(preferred-suffix-rules '(("input" . ".tex")
("include" . ".tex")
("usepackage" . ".sty")
("RequirePackageWithOptions" . ".sty")
("RequirePackage" . ".sty")
("documentclass" . ".cls")
("documentstyle" . ".cls")
("LoadClass" . ".cls")
("LoadClassWithOptions" . ".cls")
("bibliography" . ".bib")
("addbibresource" . ""))))
;; We now add preferred suffix in front of suffixes.
(when
;; The condition is essentially:
;; (assoc (TeX-current-macro)
;; (mapcar 'car preferred-suffix-rules))
;; but (TeX-current-macro) can take time, so we just
;; check if one of the `car' in preferred-suffix-rules
;; is found before point on the current line. It
;; should cover most cases.
(save-excursion
(re-search-backward (regexp-opt
(mapcar 'car preferred-suffix-rules))
(point-at-bol)
t))
(push (cons "" (cdr (assoc (match-string 0) ; i.e. "(TeX-current-macro)"
preferred-suffix-rules)))
guess-rules))
(with-temp-buffer
(let ((process-environment (buffer-local-value
'process-environment curbuf))
(exec-path (buffer-local-value 'exec-path curbuf)))
(apply #'call-process "kpsewhich" nil t nil
(mapcar (lambda (rule)
(concat (car rule) name (cdr rule)))
guess-rules)))
(when (< (point-min) (point-max))
(buffer-substring (goto-char (point-min)) (point-at-eol))))))))
(defun ffap-tex (name)