-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathelpher.el
2669 lines (2345 loc) · 110 KB
/
elpher.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
;;; elpher.el --- A friendly gopher and gemini client -*- lexical-binding: t -*-
;; Copyright (C) 2019-2024 Elpher contributors (See info manual for full list)
;; Author: Tim Vaughan <plugd@thelambdalab.xyz>
;; Created: 11 April 2019
;; Version: 3.6.4
;; Keywords: comm gopher gemini
;; Homepage: https://thelambdalab.xyz/elpher
;; Package-Requires: ((emacs "27.1"))
;; This file is not part of GNU Emacs.
;; This program 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.
;; This program 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 this file. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Elpher aims to provide a practical and friendly gopher and gemini
;; client for GNU Emacs. It supports:
;; - intuitive keyboard and mouse-driven browsing,
;; - out-of-the-box compatibility with evil-mode,
;; - clickable web and gopher links *in plain text*,
;; - caching of visited sites,
;; - pleasant and configurable colouring of Gopher directories,
;; - direct visualisation of image files,
;; - gopher connections using TLS encryption,
;; - the fledgling Gemini protocol,
;; - the greybeard Finger protocol.
;; To launch Elpher, simply use 'M-x elpher'. This will open a start
;; page containing information on key bindings and suggested starting
;; points for your gopher exploration.
;; Full instructions can be found in the Elpher info manual.
;; Elpher is under active development. Any suggestions for
;; improvements are welcome, and can be made on the official project
;; page, gopher://thelambdalab.xyz/1/projects/elpher, or via the
;; project mailing list at https://lists.sr.ht/~michel-slm/elpher.
;;; Code:
(provide 'elpher)
;;; Dependencies
;;
(require 'seq)
(require 'shr)
(require 'url-util)
(require 'subr-x)
(require 'nsm)
(require 'gnutls)
(require 'socks)
(require 'bookmark)
(require 'rx)
;;; Global constants
;;
(defconst elpher-version "3.6.4"
"Current version of elpher.")
(defconst elpher-margin-width 6
"Width of left-hand margin used when rendering indicies.")
(defconst elpher-type-map
'(((gopher ?0) elpher-get-gopher-page elpher-render-text "txt" elpher-text)
((gopher ?1) elpher-get-gopher-page elpher-render-index "/" elpher-index)
((gopher ?4) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
((gopher ?5) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
((gopher ?7) elpher-get-gopher-query-page elpher-render-index "?" elpher-search)
((gopher ?9) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
((gopher ?g) elpher-get-gopher-page elpher-render-image "img" elpher-image)
((gopher ?p) elpher-get-gopher-page elpher-render-image "img" elpher-image)
((gopher ?I) elpher-get-gopher-page elpher-render-image "img" elpher-image)
((gopher ?d) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
((gopher ?P) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
((gopher ?s) elpher-get-gopher-page elpher-render-download "snd" elpher-binary)
((gopher ?h) elpher-get-gopher-page elpher-render-html "htm" elpher-html)
(gemini elpher-get-gemini-page elpher-render-gemini "gem" elpher-gemini)
(finger elpher-get-finger-page elpher-render-text "txt" elpher-text)
(telnet elpher-get-telnet-page nil "tel" elpher-telnet)
(other-url elpher-get-other-url-page nil "url" elpher-other-url)
(file elpher-get-file-page nil "~" elpher-gemini)
((about welcome) elpher-get-welcome-page nil "E" elpher-index)
((about bookmarks) elpher-get-bookmarks-page nil "E" elpher-index)
((about history) elpher-get-history-page nil "E" elpher-index)
((about visited-pages) elpher-get-visited-pages-page nil "E" elpher-index))
"Association list from types to getters, renderers, margin codes and index faces.")
;;; Declarations to avoid compiler warnings.
;;
(eval-when-compile
(declare-function ansi-color-filter-apply "ansi-color")
(declare-function ansi-color-apply "ansi-color")
(declare-function bookmark-store "bookmark")
(declare-function org-link-store-props "ol")
(declare-function org-link-set-parameters "ol")
(defvar ansi-color-context)
(defvar xterm-color--current-fg)
(defvar xterm-color--current-bg)
(defvar bookmark-make-record-function)
(defvar mu4e~view-beginning-of-url-regexp)
(defvar eww-use-browse-url)
(defvar thing-at-point-uri-schemes))
;;; Customization group
;;
(defgroup elpher nil
"A gopher and gemini client."
:group 'applications)
;; General appearance and customizations
(defcustom elpher-open-urls-with-eww nil
"If non-nil, open URL selectors using eww.
Otherwise, use the system browser via the `browse-url' function."
:type '(boolean))
(defcustom elpher-use-header t
"If non-nil, display current page information in buffer header."
:type '(boolean))
(defcustom elpher-auto-disengage-TLS nil
"If non-nil, automatically disengage TLS following an unsuccessful connection.
While enabling this may seem convenient, it is also potentially
dangerous as it allows switching from an encrypted channel back to
plain text without user input."
:type '(boolean))
(defcustom elpher-connection-timeout 5
"Specifies the number of seconds to wait for a network connection to time out."
:type '(integer))
(defcustom elpher-filter-ansi-from-text nil
"If non-nil, filter ANSI escape sequences from text.
The default behaviour is to use the ansi-color package (or xterm-color if it is
available) to interpret these sequences."
:type '(boolean))
(defcustom elpher-certificate-directory
(file-name-as-directory (locate-user-emacs-file "elpher-certificates"))
"Specify the name of the directory where client certificates will be stored.
These certificates may be used for establishing authenticated TLS connections."
:type '(directory))
(defcustom elpher-openssl-command "openssl"
"The command used to launch openssl when generating TLS client certificates."
:type '(file))
(defcustom elpher-default-url-type "gopher"
"Default URL type (i.e. scheme) to assume if not explicitly given."
:type '(choice (const "gopher")
(const "gemini")))
(defcustom elpher-gemini-TLS-cert-checks nil
"If non-nil, verify gemini server TLS certs using the default security level.
Otherwise, certificate verification is disabled.
This defaults to off because it is standard practice for Gemini servers
to use self-signed certificates, meaning that most servers provide what
EMACS considers to be an invalid certificate."
:type '(boolean))
(defcustom elpher-gemini-max-fill-width 80
"Specify the maximum default width (in columns) of text/gemini documents.
The actual width used is the minimum of this value and the window width at
the time when the text is rendered."
:type '(integer))
(defcustom elpher-gemini-link-string "→ "
"Specify the string used to indicate links when rendering gemini maps.
May be empty."
:type '(string))
(defcustom elpher-gemini-bullet-string "•"
"Specify the string used for bullets when rendering gemini maps."
:type '(string))
(defcustom elpher-ipv4-always nil
"If non-nil, elpher will always use IPv4 to establish network connections.
This can be useful when browsing from a computer that supports IPv6, because
some servers which do not support IPv6 can take a long time to time-out."
:type '(boolean))
(defcustom elpher-socks-always nil
"If non-nil, elpher will establish network connections over a SOCKS proxy.
Otherwise, the SOCKS proxy is only used for connections to onion services."
:type '(boolean))
(defcustom elpher-use-emacs-bookmark-menu nil
"If non-nil, elpher will only use the native Emacs bookmark menu.
Otherwise, \\[elpher-show-bookmarks] will visit a special elpher bookmark
page within which all of the standard elpher keybindings are active."
:type '(boolean))
(defcustom elpher-start-page-url "about:welcome"
"Specify the page displayed initially by elpher.
The default welcome screen is \"about:welcome\", while the bookmarks list
is \"about:bookmarks\". You can also specify local files via \"file:\".
Beware that using \"about:bookmarks\" as a start page in combination with
the `elpher-use-bookmark-menu' variable set to non-nil will prevent the
Emacs bookmark menu being accessible via \\[elpher-show-bookmarks] from
the start page."
:type '(string))
(defcustom elpher-gemini-hide-preformatted nil
"Cause elpher to hide preformatted gemini text by default.
When this option is enabled, preformatted text in text/gemini documents
is replaced with a button which can be used to toggle its display.
This is intended to improve accessibility, as preformatted text often
includes art which can be difficult for screen readers to interpret
meaningfully."
:type '(boolean))
(defcustom elpher-gemini-preformatted-toggle-bullet "‣ "
"Margin symbol used to distinguish the preformatted text toggle."
:type '(string))
(defcustom elpher-gemini-preformatted-toggle-label "[Toggle Preformatted Text]"
"Label of button used to toggle formatted text."
:type '(string))
(defcustom elpher-certificate-map nil
"Register client certificates to be used for gemini URLs.
This variable contains an alist representing a mapping between gemini
URLs and the names of client certificates which will be automatically
activated for those URLs. Beware that the certificates will also be
active for all subdirectories of the given URLs."
:type '(alist :key-type string :value-type string))
;; Face customizations
(defgroup elpher-faces nil
"Elpher face customizations."
:group 'elpher)
(defface elpher-index
'((t :inherit font-lock-keyword-face))
"Face used for directory type directory records.")
(defface elpher-text
'((t :inherit bold))
"Face used for text type directory records.")
(defface elpher-info
'((t :inherit default))
"Face used for info type directory records.")
(defface elpher-image
'((t :inherit font-lock-string-face))
"Face used for image type directory records.")
(defface elpher-search
'((t :inherit warning))
"Face used for search type directory records.")
(defface elpher-html
'((t :inherit font-lock-comment-face))
"Face used for html type directory records.")
(defface elpher-gemini
'((t :inherit font-lock-constant-face))
"Face used for Gemini type directory records.")
(defface elpher-other-url
'((t :inherit font-lock-comment-face))
"Face used for other URL type links records.")
(defface elpher-telnet
'((t :inherit font-lock-function-name-face))
"Face used for telnet type directory records.")
(defface elpher-binary
'((t :inherit font-lock-doc-face))
"Face used for binary type directory records.")
(defface elpher-unknown
'((t :inherit error))
"Face used for directory records with unknown/unsupported types.")
(defface elpher-margin-key
'((t :inherit bold))
"Face used for directory margin key.")
(defface elpher-margin-brackets
'((t :inherit shadow))
"Face used for brackets around directory margin key.")
(defface elpher-gemini-heading1
'((t :inherit bold :height 1.8))
"Face used for gemini heading level 1.")
(defface elpher-gemini-heading2
'((t :inherit bold :height 1.5))
"Face used for gemini heading level 2.")
(defface elpher-gemini-heading3
'((t :inherit bold :height 1.2))
"Face used for gemini heading level 3.")
(defface elpher-gemini-quoted
'((t :inherit font-lock-doc-face))
"Face used for gemini quoted texts.")
(defface elpher-gemini-preformatted
'((t :inherit default))
"Face used for gemini preformatted text.")
(defface elpher-gemini-preformatted-toggle
'((t :inherit button))
"Face used for buttons used to toggle display of preformatted text.")
;;; Model
;;
;; Address
;; An elpher "address" object is either a url object or a symbol.
;; Addresses with the "about" type, corresponding to pages generated
;; dynamically for and by elpher. All others represent pages which
;; rely on content retrieved over the network.
(defun elpher-address-from-url (url-string &optional default-scheme)
"Create a ADDRESS object corresponding to the given URL-STRING.
If DEFAULT-SCHEME is non-nil, this sets the scheme of the URL when one
is not explicitly given."
(let ((data (match-data))) ; Prevent parsing clobbering match data
(unwind-protect
(let ((url (url-generic-parse-url url-string)))
(unless (and (not (url-fullness url)) (url-type url))
(unless (url-type url)
(setf (url-type url) default-scheme))
(unless (url-host url)
(let ((p (split-string (url-filename url) "/" nil nil)))
(setf (url-host url) (car p))
(setf (url-filename url)
(if (cdr p)
(concat "/" (mapconcat #'identity (cdr p) "/"))
""))))
(when (not (string-empty-p (url-host url)))
(setf (url-fullness url) t)
(setf (url-host url) (puny-encode-domain (url-host url))))
(when (or (equal "gopher" (url-type url))
(equal "gophers" (url-type url)))
;; Gopher defaults
(when (or (equal (url-filename url) "")
(equal (url-filename url) "/"))
(setf (url-filename url) "/1")))
(when (equal "gemini" (url-type url))
;; Gemini defaults
(if (equal (url-filename url) "")
(setf (url-filename url) "/"))))
(elpher-remove-redundant-ports url))
(set-match-data data))))
(defun elpher-remove-redundant-ports (address)
"Remove redundant port specifiers from ADDRESS.
Here `redundant' means that the specified port matches the default
for that protocol, eg 70 for gopher."
(if (and (not (elpher-address-about-p address))
(eq (url-portspec address) ; (url-port) is too slow!
(pcase (url-type address)
("gemini" 1965)
((or "gopher" "gophers") 70)
("finger" 79)
(_ -1))))
(setf (url-portspec address) nil))
address)
(defun elpher-make-gopher-address (type selector host port &optional tls)
"Create an ADDRESS object using gopher directory record attributes.
The basic attributes include: TYPE, SELECTOR, HOST and PORT.
If the optional attribute TLS is non-nil, the address will be marked as
requiring gopher-over-TLS."
(cond
((equal type ?i) nil)
((and (equal type ?h)
(string-prefix-p "URL:" selector))
(elpher-address-from-url (elt (split-string selector "URL:") 1)))
((equal type ?8)
(elpher-address-from-url
(concat "telnet"
"://" host
":" (number-to-string port))))
(t
(elpher-address-from-url
(concat "gopher" (if tls "s" "")
"://" host
":" (number-to-string port)
"/" (string type)
selector)))))
(defun elpher-make-about-address (type)
"Create an ADDRESS object corresponding to the given about address TYPE."
(elpher-address-from-url (concat "about:" (symbol-name type))))
(defun elpher-address-to-url (address)
"Get string representation of ADDRESS."
(url-encode-url (url-recreate-url address)))
(defun elpher-address-type (address)
"Retrieve type of ADDRESS object.
This is used to determine how to retrieve and render the document the
address refers to, via the table `elpher-type-map'."
(pcase (url-type address)
("about"
(list 'about (intern (url-filename address))))
((or "gopher" "gophers")
(list 'gopher
(if (member (url-filename address) '("" "/"))
?1
(string-to-char (substring (url-filename address) 1)))))
("gemini" 'gemini)
("telnet" 'telnet)
("finger" 'finger)
("file" 'file)
(_ 'other-url)))
(defun elpher-address-about-p (address)
"Return non-nil if ADDRESS is an about address."
(pcase (elpher-address-type address) (`(about ,_) t)))
(defun elpher-address-gopher-p (address)
"Return non-nil if ADDRESS object is a gopher address."
(pcase (elpher-address-type address) (`(gopher ,_) t)))
(defun elpher-address-protocol (address)
"Retrieve the transport protocol for ADDRESS."
(url-type address))
(defun elpher-address-filename (address)
"Retrieve the filename component of ADDRESS.
For gopher addresses this is a combination of the selector type and selector."
(url-unhex-string (url-filename address)))
(defun elpher-address-host (address)
"Retrieve host from ADDRESS object."
(pcase (url-host address)
;; The following strips out square brackets which sometimes enclose IPv6
;; addresses. Doing this here rather than at the parsing stage may seem
;; weird, but this lets us way we avoid having to muck with both URL parsing
;; and reconstruction. It's also more efficient, as this method is not
;; called during page rendering.
((rx (: "[" (let ipv6 (* (not "]"))) "]"))
ipv6)
;; The following is a work-around for a parsing bug that causes
;; URLs with empty (but not absent, see RFC 1738) usernames to have
;; @ prepended to the hostname.
((rx (: "@" (let rest (+ anything))))
rest)
(addr
addr)))
(defun elpher-address-user (address)
"Retrieve user from ADDRESS object."
(url-user address))
(defun elpher-address-port (address)
"Retrieve port from ADDRESS object.
If no address is defined, returns 0. (This is for compatibility with
the URL library.)"
(let ((port (url-portspec address))) ; (url-port) is too slow!
(if port port 0)))
(defun elpher-gopher-address-selector (address)
"Retrieve gopher selector from ADDRESS object."
(if (member (url-filename address) '("" "/"))
""
(url-unhex-string (substring (url-filename address) 2))))
;; Cache
(defvar elpher-content-cache (make-hash-table :test 'equal))
(defvar elpher-pos-cache (make-hash-table :test 'equal))
(defun elpher-get-cached-content (address)
"Retrieve the cached content for ADDRESS, or nil if none exists."
(gethash address elpher-content-cache))
(defun elpher-cache-content (address content)
"Set the content cache for ADDRESS to CONTENT."
(puthash address content elpher-content-cache))
(defun elpher-get-cached-pos (address)
"Retrieve the cached cursor position for ADDRESS, or nil if none exists."
(gethash address elpher-pos-cache))
(defun elpher-cache-pos (address pos)
"Set the cursor position cache for ADDRESS to POS."
(puthash address pos elpher-pos-cache))
;; Page
(defun elpher-make-page (display-string address)
"Create a page with DISPLAY-STRING and ADDRESS."
(list display-string address))
(defun elpher-make-start-page ()
"Create the start page."
(elpher-make-page "Start Page"
(elpher-address-from-url elpher-start-page-url)))
(defun elpher-page-display-string (page)
"Retrieve the display string corresponding to PAGE."
(elt page 0))
(defun elpher-page-address (page)
"Retrieve the address corresponding to PAGE."
(elt page 1))
(defun elpher-page-set-address (page new-address)
"Set the address corresponding to PAGE to NEW-ADDRESS."
(setcar (cdr page) new-address))
(defun elpher-page-from-url (url &optional default-scheme)
"Create a page with address and display string defined by URL.
The URL is unhexed prior to its use as a display string to improve
readability.
If DEFAULT-SCHEME is non-nil, this scheme is applied to the URL
in the instance that URL itself doesn't specify one."
(let ((address (elpher-address-from-url url default-scheme)))
(elpher-make-page (elpher-address-to-iri address) address)))
(defun elpher-address-to-iri (address)
"Return an IRI for ADDRESS.
Decode percent-escapes and handle punycode in the domain name.
Drop the password, if any."
(let ((data (match-data)) ; Prevent parsing clobbering match data
(host (url-host address))
(pass (url-password address)))
(unwind-protect
(let* ((host (url-host address))
(pass (url-password address)))
(when host
(setf (url-host address) (puny-decode-domain host)))
(when pass ; RFC 3986 says we should not render
(setf (url-password address) nil)) ; the password as clear text
(elpher-decode (url-unhex-string (url-recreate-url address))))
(setf (url-host address) host)
(setf (url-password address) pass)
(set-match-data data))))
(defvar elpher-current-page nil
"The current page for this Elpher buffer.")
(defvar elpher-history nil
"The local history stack for this Elpher buffer.
This variable is used by `elpher-back' and
`elpher-show-history'.")
(defvar elpher-visited-pages nil
"The global history for all Elpher buffers.
This variable is used by `elpher-show-visited-pages'.")
(defun elpher-visit-page (page &optional renderer no-history)
"Visit PAGE using its own renderer or RENDERER, if non-nil.
Additionally, push PAGE onto the history stack and the list of
previously-visited pages, unless NO-HISTORY is non-nil."
(elpher-save-pos)
(elpher-process-cleanup)
(unless no-history
(unless (or (not elpher-current-page)
(equal (elpher-page-address elpher-current-page)
(elpher-page-address page)))
(push elpher-current-page elpher-history)
(unless (or (elpher-address-about-p (elpher-page-address page))
(and elpher-visited-pages
(equal page (car elpher-visited-pages))))
(push page elpher-visited-pages))))
(setq-local elpher-current-page page)
(let* ((address (elpher-page-address page))
(type (elpher-address-type address))
(type-record (cdr (assoc type elpher-type-map))))
(if type-record
(funcall (car type-record)
(if renderer
renderer
(cadr type-record)))
(elpher-visit-previous-page)
(pcase type
(`(gopher ,type-char)
(error "Unsupported gopher selector type '%c' for '%s'"
type-char (elpher-address-to-url address)))
(other
(error "Unsupported address type '%S' for '%s'"
other (elpher-address-to-url address)))))))
(defun elpher-visit-previous-page ()
"Visit the previous page in the history."
(if elpher-history
(elpher-visit-page (pop elpher-history) nil t)
(error "No previous page")))
(defun elpher-reload-current-page ()
"Reload the current page, discarding any existing cached content."
(elpher-cache-content (elpher-page-address elpher-current-page) nil)
(elpher-visit-page elpher-current-page))
(defun elpher-save-pos ()
"Save the current position of point to the current page."
(when elpher-current-page
(elpher-cache-pos (elpher-page-address elpher-current-page) (point))))
(defun elpher-restore-pos ()
"Restore the position of point to that cached in the current page."
(let ((pos (elpher-get-cached-pos (elpher-page-address elpher-current-page))))
(if pos
(goto-char pos)
(goto-char (point-min)))))
(defun elpher-get-default-url-scheme ()
"Suggest default URL scheme for visiting addresses based on the current page."
(if elpher-current-page
(let* ((address (elpher-page-address elpher-current-page))
(current-type (elpher-address-type address)))
(pcase current-type
((or (and 'file (guard (not elpher-history)))
`(about ,_))
elpher-default-url-type)
(_
(url-type address))))
elpher-default-url-type))
;;; Buffer preparation
;;
(defvar elpher-buffer-name "*elpher*"
"The default name of the Elpher buffer.")
(defun elpher-update-header ()
"If `elpher-use-header' is true, display current page info in window header."
(if (and elpher-use-header elpher-current-page)
(let* ((display-string (elpher-page-display-string elpher-current-page))
(sanitized-display-string (replace-regexp-in-string "%" "%%" display-string))
(address (elpher-page-address elpher-current-page))
(tls-string (if (and (not (elpher-address-about-p address))
(member (elpher-address-protocol address)
'("gophers" "gemini")))
" [TLS encryption]"
""))
(header (concat sanitized-display-string
(propertize tls-string 'face 'bold))))
(setq header-line-format header))))
(defmacro elpher-with-clean-buffer (&rest args)
"Evaluate ARGS with a clean *elpher* buffer as current."
(declare (debug (body))) ;; Allow edebug to step through body
`(with-current-buffer elpher-buffer-name
(unless (eq major-mode 'elpher-mode)
;; avoid resetting buffer-local variables
(elpher-mode))
(let ((inhibit-read-only t)
(ansi-color-context nil)) ;; clean ansi interpreter state (also next 2 lines)
(setq-local xterm-color--current-fg nil)
(setq-local xterm-color--current-bg nil)
(setq-local network-security-level
(default-value 'network-security-level))
(erase-buffer)
(elpher-update-header)
,@args)))
(defun elpher-buffer-message (string &optional line)
"Replace first line in elpher buffer with STRING.
If LINE is non-nil, replace that line instead."
(with-current-buffer elpher-buffer-name
(let ((inhibit-read-only t))
(goto-char (point-min))
(if line
(forward-line line))
(let ((data (match-data)))
(unwind-protect
(progn
(re-search-forward "^.*$")
(replace-match string))
(set-match-data data))))))
;;; Link button definitions
;;
(defvar elpher-link-keymap
(let ((map (make-sparse-keymap)))
(define-key map (kbd "S-<down-mouse-1>") 'ignore) ;Prevent buffer face popup
(define-key map (kbd "S-<mouse-1>") #'elpher--open-link-new-buffer-mouse)
(define-key map (kbd "S-<return>") #'elpher--open-link-new-buffer)
(set-keymap-parent map button-map)
map))
(defun elpher--click-link (button)
"Function called when the gopher link BUTTON is activated."
(let ((page (button-get button 'elpher-page)))
(elpher-visit-page page)))
(defun elpher--open-link-new-buffer ()
"Internal function used by Elpher to open links in a new buffer."
(interactive)
(let ((page (button-get (button-at (point)) 'elpher-page))
(new-buf (generate-new-buffer (default-value 'elpher-buffer-name))))
(pop-to-buffer new-buf)
(elpher-mode)
(elpher-visit-page page)))
(defun elpher--open-link-new-buffer-mouse (event)
"Internal function used by Elpher to open links in a new buffer.
The EVENT argument is the mouse event which caused this function to be
called."
(interactive "e")
(mouse-set-point event)
(elpher--open-link-new-buffer))
(defun elpher--page-button-help (_window buffer pos)
"Function called by Emacs to generate mouse-over text.
The arguments specify the BUFFER and the POS within the buffer of the item
for which help is required. The function returns the help to be
displayed. The _WINDOW argument is currently unused."
(with-current-buffer buffer
(let ((button (button-at pos)))
(when button
(let* ((page (button-get button 'elpher-page))
(address (elpher-page-address page)))
(format "mouse-1, RET: open '%s'" (elpher-address-to-url address)))))))
(define-button-type 'elpher-link
'action #'elpher--click-link
'keymap elpher-link-keymap
'follow-link t
'help-echo #'elpher--page-button-help
'face 'button)
;;; Text Processing
;;
(defvar elpher-user-coding-system nil
"User-specified coding system to use for decoding text responses.")
(defun elpher-decode (string)
"Decode STRING using autodetected or user-specified coding system."
(decode-coding-string string
(if elpher-user-coding-system
elpher-user-coding-system
(detect-coding-string string t))))
(defun elpher-preprocess-text-response (string)
"Preprocess text selector response contained in STRING.
This involes decoding the character representation, and clearing
away CRs and any terminating period."
(elpher-decode (replace-regexp-in-string "\n\\.\n$" "\n"
(replace-regexp-in-string "\r" "" string))))
;;; Buttonify urls
(defconst elpher-url-regex
"\\([a-zA-Z]+\\)://\\([a-zA-Z0-9.-]*[a-zA-Z0-9-]\\|\\[[a-zA-Z0-9:]+\\]\\)\\(:[0-9]+\\)?\\(/\\([0-9a-zA-Z_~?/@|:.%#=&-]*[0-9a-zA-Z_~?/@|#-]\\)?\\)?"
"Regexp used to locate and buttonify URLs in text files loaded by elpher.")
(defun elpher-buttonify-urls (string)
"Turn substrings which look like urls in STRING into clickable buttons."
(with-temp-buffer
(insert string)
(goto-char (point-min))
(while (re-search-forward elpher-url-regex nil t)
(let ((page (elpher-page-from-url (substring-no-properties (match-string 0)))))
(make-text-button (match-beginning 0)
(match-end 0)
'elpher-page page
:type 'elpher-link)))
(buffer-string)))
;; ANSI colors or XTerm colors (application and filtering)
(or (require 'xterm-color nil t)
(require 'ansi-color))
(defalias 'elpher-color-filter-apply
(if (fboundp 'xterm-color-filter)
(lambda (s)
(let ((_xterm-color-render nil))
(xterm-color-filter s)))
#'ansi-color-filter-apply)
"A function to filter out ANSI escape sequences.")
(defalias 'elpher-color-apply
(if (fboundp 'xterm-color-filter)
#'xterm-color-filter
#'ansi-color-apply)
"A function to apply ANSI escape sequences.")
(defun elpher-text-has-ansi-escapes-p (string)
"Return non-nil if STRING includes an ANSI escape code."
(save-match-data
(string-match "\x1b\\[" string)))
;; Processing text for display
(defun elpher-process-text-for-display (string)
"Perform any desired processing of STRING prior to display as text.
Currently includes buttonifying URLs and processing ANSI escape codes."
(elpher-buttonify-urls (if (elpher-text-has-ansi-escapes-p string)
(if elpher-filter-ansi-from-text
(elpher-color-filter-apply string)
(elpher-color-apply string))
string)))
;;; General network communication
;;
(defun elpher-network-error (address error)
"Display ERROR message following unsuccessful negotiation with ADDRESS.
ERROR can be either an error object or a string."
(elpher-with-clean-buffer
(insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
"When attempting to retrieve " (elpher-address-to-url address) ":\n"
(if (stringp error) error (error-message-string error)) "\n"
(propertize "\n----------------\n\n" 'face 'error)
"Press 'u' to return to the previous page.")))
(defvar elpher-network-timer nil
"Timer used for network connections.")
(defvar elpher-use-tls nil
"If non-nil, use TLS to communicate with gopher servers.")
(defvar elpher-client-certificate nil
"If non-nil, contains client certificate details to use for TLS connections.")
(defun elpher-process-cleanup ()
"Immediately shut down any extant elpher process and timers."
(let ((p (get-process "elpher-process")))
(if p (delete-process p)))
(if (timerp elpher-network-timer)
(cancel-timer elpher-network-timer)))
(defun elpher-make-network-timer (thunk)
"Create a timer to run the THUNK after `elpher-connection-timeout' seconds.
This is just a wraper around `run-at-time' which additionally sets the
buffer-local variable `elpher-network-timer' to allow
`elpher-process-cleanup' to also clear the timer."
(let ((timer (run-at-time elpher-connection-timeout nil thunk)))
(setq-local elpher-network-timer timer)
timer))
(defun elpher-get-host-response (address default-port query-string response-processor
&optional use-tls force-ipv4)
"Generic function for retrieving data from ADDRESS.
When ADDRESS lacks a specific port, DEFAULT-PORT is used instead.
QUERY-STRING is a string sent to the host specified by ADDRESS to
illicet a response. This response is passed as an argument to the
function RESPONSE-PROCESSOR.
If non-nil, USE-TLS specifies that the connection is to be made over
TLS. If set to gemini, the certificate verification will be disabled
unless `elpher-gemini-TLS-cert-checks' is non-nil.
If non-nil, FORCE-IPV4 causes the network connection to be made over
ipv4 only. (The default behaviour when this is not set depends on
the host operating system and the local network capabilities.)"
(if (and use-tls (not (gnutls-available-p)))
(error "Use of TLS requires Emacs to be compiled with GNU TLS support")
(unless (< (elpher-address-port address) 65536)
(error "Cannot establish network connection: port number > 65536"))
(when (and (eq use-tls 'gemini) (not elpher-gemini-TLS-cert-checks))
(setq-local network-security-level 'low)
(setq-local gnutls-verify-error nil))
(condition-case nil
(let* ((kill-buffer-query-functions nil)
(port (elpher-address-port address))
(host (elpher-address-host address))
(service (if (> port 0) port default-port))
(response-string-parts nil)
(bytes-received 0)
(hkbytes-received 0)
(socks (or elpher-socks-always (string-suffix-p ".onion" host)))
(gnutls-params (list :type 'gnutls-x509pki
:hostname host
:keylist
(elpher-get-current-keylist address)))
(timer (elpher-make-network-timer
(lambda ()
(elpher-process-cleanup)
(cond
; Try again with IPv4
((not (or elpher-ipv4-always force-ipv4 socks))
(message "Connection timed out. Retrying with IPv4.")
(elpher-get-host-response address default-port
query-string
response-processor
use-tls t))
((and use-tls
(not (eq use-tls 'gemini))
(or elpher-auto-disengage-TLS
(y-or-n-p
"TLS connetion failed. Disable TLS mode and retry? ")))
(setq elpher-use-tls nil)
(elpher-get-host-response address default-port
query-string
response-processor
nil force-ipv4))
(t
(elpher-network-error address "Connection time-out."))))))
(proc (if socks
(socks-open-network-stream "elpher-process" nil host service)
(make-network-process :name "elpher-process"
:host host
:family (and (or force-ipv4
elpher-ipv4-always)
'ipv4)
:service service
:buffer nil
:nowait t
:tls-parameters
(and use-tls
(cons 'gnutls-x509pki
(apply #'gnutls-boot-parameters
gnutls-params)))))))
(process-put proc 'elpher-buffer (current-buffer))
(setq elpher-network-timer timer)
(set-process-coding-system proc 'binary 'binary)
(set-process-query-on-exit-flag proc nil)
(elpher-buffer-message (concat "Connecting to " host "..."
" (press 'u' to abort)"))
(set-process-filter proc
(lambda (_proc string)
(when timer
(cancel-timer timer)
(setq timer nil))
(setq bytes-received (+ bytes-received (length string)))
(let ((new-hkbytes-received (/ bytes-received 102400)))
(when (> new-hkbytes-received hkbytes-received)
(setq hkbytes-received new-hkbytes-received)
(elpher-buffer-message
(concat "("
(number-to-string (/ hkbytes-received 10.0))
" MB read)")
1)))
(setq response-string-parts
(cons string response-string-parts))))
(set-process-sentinel proc
(lambda (proc event)
(when timer
(cancel-timer timer))
(condition-case the-error
(cond
((string-prefix-p "open" event) ; request URL
(elpher-buffer-message
(concat "Connected to " host ". Receiving data..."
" (press 'u' to abort)"))
(let ((inhibit-eol-conversion t))
(process-send-string proc query-string)))
((string-prefix-p "deleted" event)) ; do nothing
((and (not response-string-parts)
(not (or elpher-ipv4-always force-ipv4 socks)))
; Try again with IPv4
(message "Connection failed. Retrying with IPv4.")
(elpher-get-host-response address default-port
query-string
response-processor
use-tls t))
(response-string-parts
(with-current-buffer (process-get proc 'elpher-buffer)
(elpher-with-clean-buffer
(insert "Data received. Rendering..."))
(funcall response-processor
(apply #'concat (reverse response-string-parts)))
(elpher-restore-pos)))
(t
(error "No response from server")))
(error
(elpher-network-error address the-error)))))
(when socks
(when use-tls
(apply #'gnutls-negotiate :process proc gnutls-params)
(unless (or (< emacs-major-version 31)