Use xterm-color instead of ansi-color, if possible
[elpher.git] / elpher.el
1 ;;; elpher.el --- A friendly gopher and gemini client  -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2021 Jens Östlund <jostlund@gmail.com>
4 ;; Copyright (C) 2021 F. Jason Park <jp@neverwas.me>
5 ;; Copyright (C) 2021 Christopher Brannon <chris@the-brannons.com>
6 ;; Copyright (C) 2021 Omar Polo <op@omarpolo.com>
7 ;; Copyright (C) 2021 Noodles! <nnoodle@chiru.no>
8 ;; Copyright (C) 2020-2021 Alex Schroeder <alex@gnu.org>
9 ;; Copyright (C) 2020 Étienne Deparis <etienne@depar.is>
10 ;; Copyright (C) 2020 Simon Nicolussi <sinic@sinic.name>
11 ;; Copyright (C) 2020 Michel Alexandre Salim <michel@michel-slm.name>
12 ;; Copyright (C) 2020 Koushk Roy <kroy@twilio.com>
13 ;; Copyright (C) 2020 Vee <vee@vnsf.xyz>
14 ;; Copyright (C) 2020 Simon South <simon@simonsouth.net>
15 ;; Copyright (C) 2019-2020 Tim Vaughan <plugd@thelambdalab.xyz>
16
17 ;; Author: Tim Vaughan <plugd@thelambdalab.xyz>
18 ;; Created: 11 April 2019
19 ;; Version: 2.11.0
20 ;; Keywords: comm gopher
21 ;; Homepage: http://thelambdalab.xyz/elpher
22 ;; Package-Requires: ((emacs "26.2"))
23
24 ;; This file is not part of GNU Emacs.
25
26 ;; This program is free software: you can redistribute it and/or modify
27 ;; it under the terms of the GNU General Public License as published by
28 ;; the Free Software Foundation, either version 3 of the License, or
29 ;; (at your option) any later version.
30
31 ;; This program is distributed in the hope that it will be useful,
32 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
33 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34 ;; GNU General Public License for more details.
35
36 ;; You should have received a copy of the GNU General Public License
37 ;; along with this file.  If not, see <http://www.gnu.org/licenses/>.
38
39 ;;; Commentary:
40
41 ;; Elpher aims to provide a practical and friendly gopher and gemini
42 ;; client for GNU Emacs.  It supports:
43
44 ;; - intuitive keyboard and mouse-driven browsing,
45 ;; - out-of-the-box compatibility with evil-mode,
46 ;; - clickable web and gopher links *in plain text*,
47 ;; - caching of visited sites,
48 ;; - pleasant and configurable colouring of Gopher directories,
49 ;; - direct visualisation of image files,
50 ;; - a simple bookmark management system,
51 ;; - gopher connections using TLS encryption,
52 ;; - the fledgling Gemini protocol,
53 ;; - the greybeard Finger protocol.
54
55 ;; To launch Elpher, simply use 'M-x elpher'.  This will open a start
56 ;; page containing information on key bindings and suggested starting
57 ;; points for your gopher exploration.
58
59 ;; Full instructions can be found in the Elpher info manual.
60
61 ;; Elpher is under active development.  Any suggestions for
62 ;; improvements are welcome, and can be made on the official
63 ;; project page, gopher://thelambdalab.xyz/1/projects/elpher/.
64
65 ;;; Code:
66
67 (provide 'elpher)
68
69 ;;; Dependencies
70 ;;
71
72 (require 'seq)
73 (require 'pp)
74 (require 'shr)
75 (require 'url-util)
76 (require 'subr-x)
77 (require 'dns)
78 (require 'nsm)
79 (require 'gnutls)
80 (require 'socks)
81
82 ;;; ANSI colors or XTerm colors
83
84 (or (require 'xterm-color nil t)
85     (require 'ansi-color))
86
87 (defalias 'elpher-color-filter-apply
88   (if (fboundp 'xterm-color-filter)
89       (lambda (s)
90         (let ((xterm-color-render nil))
91           (xterm-color-filter s)))
92     'ansi-color-filter-apply)
93   "A function to filter out ANSI escape sequences.")
94 (defalias 'elpher-color-apply
95   (if (fboundp 'xterm-color-filter)
96       'xterm-color-filter
97     'ansi-color-apply)
98   "A function to apply ANSI escape sequences.")
99
100 ;;; Global constants
101 ;;
102
103 (defconst elpher-version "2.10.2"
104   "Current version of elpher.")
105
106 (defconst elpher-margin-width 6
107   "Width of left-hand margin used when rendering indicies.")
108
109 (defconst elpher-type-map
110   '(((gopher ?0) elpher-get-gopher-page elpher-render-text "txt" elpher-text)
111     ((gopher ?1) elpher-get-gopher-page elpher-render-index "/" elpher-index)
112     ((gopher ?4) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
113     ((gopher ?5) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
114     ((gopher ?7) elpher-get-gopher-query-page elpher-render-index "?" elpher-search)
115     ((gopher ?9) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
116     ((gopher ?g) elpher-get-gopher-page elpher-render-image "img" elpher-image)
117     ((gopher ?p) elpher-get-gopher-page elpher-render-image "img" elpher-image)
118     ((gopher ?I) elpher-get-gopher-page elpher-render-image "img" elpher-image)
119     ((gopher ?d) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
120     ((gopher ?P) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
121     ((gopher ?s) elpher-get-gopher-page elpher-render-download "snd" elpher-binary)
122     ((gopher ?h) elpher-get-gopher-page elpher-render-html "htm" elpher-html)
123     (gemini elpher-get-gemini-page elpher-render-gemini "gem" elpher-gemini)
124     (finger elpher-get-finger-page elpher-render-text "txt" elpher-text)
125     (telnet elpher-get-telnet-page nil "tel" elpher-telnet)
126     (other-url elpher-get-other-url-page nil "url" elpher-other-url)
127     ((special bookmarks) elpher-get-bookmarks-page nil "/" elpher-index)
128     ((special start) elpher-get-start-page nil))
129   "Association list from types to getters, renderers, margin codes and index faces.")
130
131
132 ;;; Customization group
133 ;;
134
135 (defgroup elpher nil
136   "A gopher and gemini client."
137   :group 'applications)
138
139 ;; General appearance and customizations
140
141 (defcustom elpher-open-urls-with-eww nil
142   "If non-nil, open URL selectors using eww.
143 Otherwise, use the system browser via the BROWSE-URL function."
144   :type '(boolean))
145
146 (defcustom elpher-use-header t
147   "If non-nil, display current page information in buffer header."
148   :type '(boolean))
149
150 (defcustom elpher-auto-disengage-TLS nil
151   "If non-nil, automatically disengage TLS following an unsuccessful connection.
152 While enabling this may seem convenient, it is also potentially dangerous as it
153 allows switching from an encrypted channel back to plain text without user input."
154   :type '(boolean))
155
156 (defcustom elpher-connection-timeout 5
157   "Specifies the number of seconds to wait for a network connection to time out."
158   :type '(integer))
159
160 (defcustom elpher-filter-ansi-from-text nil
161   "If non-nil, filter ANSI escape sequences from text.
162 The default behaviour is to use the ansi-color package to interpret these
163 sequences."
164   :type '(boolean))
165
166 (defcustom elpher-certificate-directory
167   (file-name-as-directory (locate-user-emacs-file "elpher-certificates"))
168   "Specify the name of the directory where client certificates will be stored.
169 These certificates may be used for establishing authenticated TLS connections."
170   :type '(directory))
171
172 (defcustom elpher-openssl-command "openssl"
173   "The command used to launch openssl when generating TLS client certificates."
174   :type '(file))
175
176 (defcustom elpher-default-url-type "gopher"
177   "Default URL type to assume if not explicitly given."
178   :type '(choice (const "gopher")
179                  (const "gemini")))
180
181 (defcustom elpher-gemini-TLS-cert-checks nil
182   "If non-nil, verify gemini server TLS certs using the default security level.
183 Otherwise, certificate verification is disabled.
184
185 This defaults to off because it is standard practice for Gemini servers
186 to use self-signed certificates, meaning that most servers provide what
187 EMACS considers to be an invalid certificate."
188   :type '(boolean))
189
190 (defcustom elpher-gemini-max-fill-width 80
191   "Specify the maximum default width (in columns) of text/gemini documents.
192 The actual width used is the minimum of this value and the window width at
193 the time when the text is rendered."
194   :type '(integer))
195
196 (defcustom elpher-gemini-link-string "→ "
197   "Specify the string used to indicate links when rendering gemini maps.
198 May be empty."
199   :type '(string))
200
201 (defcustom elpher-gemini-bullet-string "•"
202   "Specify the string used for bullets when rendering gemini maps."
203   :type '(string))
204
205 (defcustom elpher-bookmarks-file (locate-user-emacs-file "elpher-bookmarks")
206   "Specify the name of the file where elpher bookmarks will be saved."
207   :type '(file))
208
209 (defcustom elpher-ipv4-always nil
210   "If non-nil, elpher will always use IPv4 to establish network connections.
211 This can be useful when browsing from a computer that supports IPv6, because
212 some servers which do not support IPv6 can take a long time to time-out."
213   :type '(boolean))
214
215 (defcustom elpher-socks-always nil
216   "If non-nil, elpher will establish network connections over a SOCKS proxy.
217 Otherwise, the SOCKS proxy is only used for connections to onion services."
218   :type '(boolean))
219
220 ;; Face customizations
221
222 (defgroup elpher-faces nil
223   "Elpher face customizations."
224   :group 'elpher)
225
226 (defface elpher-index
227   '((t :inherit font-lock-keyword-face))
228   "Face used for directory type directory records.")
229
230 (defface elpher-text
231   '((t :inherit bold))
232   "Face used for text type directory records.")
233
234 (defface elpher-info
235   '((t :inherit default))
236   "Face used for info type directory records.")
237
238 (defface elpher-image
239   '((t :inherit font-lock-string-face))
240   "Face used for image type directory records.")
241
242 (defface elpher-search
243   '((t :inherit warning))
244   "Face used for search type directory records.")
245
246 (defface elpher-html
247   '((t :inherit font-lock-comment-face))
248   "Face used for html type directory records.")
249
250 (defface elpher-gemini
251   '((t :inherit font-lock-constant-face))
252   "Face used for Gemini type directory records.")
253
254 (defface elpher-other-url
255   '((t :inherit font-lock-comment-face))
256   "Face used for other URL type links records.")
257
258 (defface elpher-telnet
259   '((t :inherit font-lock-function-name-face))
260   "Face used for telnet type directory records.")
261
262 (defface elpher-binary
263   '((t :inherit font-lock-doc-face))
264   "Face used for binary type directory records.")
265
266 (defface elpher-unknown
267   '((t :inherit error))
268   "Face used for directory records with unknown/unsupported types.")
269
270 (defface elpher-margin-key
271   '((t :inherit bold))
272   "Face used for directory margin key.")
273
274 (defface elpher-margin-brackets
275   '((t :inherit shadow))
276   "Face used for brackets around directory margin key.")
277
278 (defface elpher-gemini-heading1
279   '((t :inherit bold :height 1.8))
280   "Face used for gemini heading level 1.")
281
282 (defface elpher-gemini-heading2
283   '((t :inherit bold :height 1.5))
284   "Face used for gemini heading level 2.")
285
286 (defface elpher-gemini-heading3
287   '((t :inherit bold :height 1.2))
288   "Face used for gemini heading level 3.")
289
290 (defface elpher-gemini-preformatted
291   '((t :inherit fixed-pitch))
292   "Face used for pre-formatted gemini text blocks.")
293
294 (defface elpher-gemini-quoted
295   '((t :inherit font-lock-doc-face))
296   "Face used for gemini quoted texts.")
297
298 ;;; Model
299 ;;
300
301 ;; Address
302
303 ;; An elpher "address" object is either a url object or a symbol.
304 ;; Symbol addresses are "special", corresponding to pages generated
305 ;; dynamically for and by elpher.  All others represent pages which
306 ;; rely on content retrieved over the network.
307
308 (defun elpher-address-from-url (url-string)
309   "Create a ADDRESS object corresponding to the given URL-STRING."
310   (let ((data (match-data))) ; Prevent parsing clobbering match data
311     (unwind-protect
312         (let ((url (url-generic-parse-url url-string)))
313           (unless (and (not (url-fullness url)) (url-type url))
314             (setf (url-fullness url) t)
315             (setf (url-filename url)
316                   (url-unhex-string (url-filename url)))
317             (unless (url-type url)
318               (setf (url-type url) elpher-default-url-type))
319             (unless (url-host url)
320               (let ((p (split-string (url-filename url) "/" nil nil)))
321                 (setf (url-host url) (car p))
322                 (setf (url-filename url)
323                       (if (cdr p)
324                           (concat "/" (mapconcat #'identity (cdr p) "/"))
325                         ""))))
326             (when (or (equal "gopher" (url-type url))
327                       (equal "gophers" (url-type url)))
328               ;; Gopher defaults
329               (when (or (equal (url-filename url) "")
330                         (equal (url-filename url) "/"))
331                 (setf (url-filename url) "/1")))
332             (when (equal "gemini" (url-type url))
333               ;; Gemini defaults
334               (if (equal (url-filename url) "")
335                   (setf (url-filename url) "/"))))
336           (elpher-remove-redundant-ports url))
337       (set-match-data data))))
338
339 (defun elpher-remove-redundant-ports (address)
340   "Remove redundant port specifiers from ADDRESS.
341 Here 'redundant' means that the specified port matches the default
342 for that protocol, eg 70 for gopher."
343   (if (and (not (elpher-address-special-p address))
344            (eq (url-portspec address) ; (url-port) is too slow!
345                (pcase (url-type address)
346                  ("gemini" 1965)
347                  ((or "gopher" "gophers") 70)
348                  ("finger" 79)
349                  (_ -1))))
350       (setf (url-portspec address) nil))
351   address)
352
353 (defun elpher-make-gopher-address (type selector host port &optional tls)
354   "Create an ADDRESS object using gopher directory record attributes.
355 The basic attributes include: TYPE, SELECTOR, HOST and PORT.
356 If the optional attribute TLS is non-nil, the address will be marked as
357 requiring gopher-over-TLS."
358   (cond
359    ((equal type ?i) nil)
360    ((and (equal type ?h)
361          (string-prefix-p "URL:" selector))
362     (elpher-address-from-url (elt (split-string selector "URL:") 1)))
363    ((equal type ?8)
364     (elpher-address-from-url
365      (concat "telnet"
366              "://" host
367              ":" (number-to-string port))))
368    (t
369     (elpher-address-from-url
370      (concat "gopher" (if tls "s" "")
371              "://" host
372              ":" (number-to-string port)
373              "/" (string type)
374              selector)))))
375
376 (defun elpher-make-special-address (type)
377   "Create an ADDRESS object corresponding to the given special address symbol TYPE."
378   type)
379
380 (defun elpher-address-to-url (address)
381   "Get string representation of ADDRESS, or nil if ADDRESS is special."
382   (if (elpher-address-special-p address)
383       nil
384     (url-encode-url (url-recreate-url address))))
385
386 (defun elpher-address-type (address)
387   "Retrieve type of ADDRESS object.
388 This is used to determine how to retrieve and render the document the
389 address refers to, via the table `elpher-type-map'."
390   (if (symbolp address)
391       (list 'special address)
392     (let ((protocol (url-type address)))
393       (cond ((or (equal protocol "gopher")
394                  (equal protocol "gophers"))
395              (list 'gopher
396                    (if (member (url-filename address) '("" "/"))
397                        ?1
398                      (string-to-char (substring (url-filename address) 1)))))
399             ((equal protocol "gemini")
400              'gemini)
401             ((equal protocol "telnet")
402              'telnet)
403             ((equal protocol "finger")
404              'finger)
405             (t 'other-url)))))
406
407 (defun elpher-address-protocol (address)
408   "Retrieve the transport protocol for ADDRESS.  This is nil for special addresses."
409   (if (symbolp address)
410       nil
411     (url-type address)))
412
413 (defun elpher-address-filename (address)
414   "Retrieve the filename component of ADDRESS.
415 For gopher addresses this is a combination of the selector type and selector."
416   (if (symbolp address)
417       nil
418     (url-filename address)))
419
420 (defun elpher-address-host (address)
421   "Retrieve host from ADDRESS object."
422   (url-host address))
423
424 (defun elpher-address-user (address)
425   "Retrieve user from ADDRESS object."
426   (url-user address))
427
428 (defun elpher-address-port (address)
429   "Retrieve port from ADDRESS object.
430 If no address is defined, returns 0.  (This is for compatibility with the URL library.)"
431   (if (symbolp address)
432       0
433     (url-port address)))
434
435 (defun elpher-address-special-p (address)
436   "Return non-nil if ADDRESS object is special (e.g. start page, bookmarks page)."
437   (symbolp address))
438
439 (defun elpher-address-gopher-p (address)
440   "Return non-nill if ADDRESS object is a gopher address."
441   (and (not (elpher-address-special-p address))
442        (member (elpher-address-protocol address) '("gopher gophers"))))
443
444 (defun elpher-gopher-address-selector (address)
445   "Retrieve gopher selector from ADDRESS object."
446   (if (member (url-filename address) '("" "/"))
447       ""
448     (url-unhex-string (substring (url-filename address) 2))))
449
450
451 ;; Cache
452
453 (defvar elpher-content-cache (make-hash-table :test 'equal))
454 (defvar elpher-pos-cache (make-hash-table :test 'equal))
455
456 (defun elpher-get-cached-content (address)
457   "Retrieve the cached content for ADDRESS, or nil if none exists."
458   (gethash address elpher-content-cache))
459
460 (defun elpher-cache-content (address content)
461   "Set the content cache for ADDRESS to CONTENT."
462   (puthash address content elpher-content-cache))
463
464 (defun elpher-get-cached-pos (address)
465   "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
466   (gethash address elpher-pos-cache))
467
468 (defun elpher-cache-pos (address pos)
469   "Set the cursor position cache for ADDRESS to POS."
470   (puthash address pos elpher-pos-cache))
471
472
473 ;; Page
474
475 (defun elpher-make-page (display-string address)
476   "Create a page with DISPLAY-STRING and ADDRESS."
477   (list display-string address))
478
479 (defun elpher-page-display-string (page)
480   "Retrieve the display string corresponding to PAGE."
481   (elt page 0))
482
483 (defun elpher-page-address (page)
484   "Retrieve the address corresponding to PAGE."
485   (elt page 1))
486
487 (defun elpher-page-set-address (page new-address)
488   "Set the address corresponding to PAGE to NEW-ADDRESS."
489   (setcar (cdr page) new-address))
490
491 (defvar elpher-current-page nil)        ; buffer local
492 (defvar elpher-history nil)             ; buffer local
493
494 (defun elpher-visit-page (page &optional renderer no-history)
495   "Visit PAGE using its own renderer or RENDERER, if non-nil.
496 Additionally, push PAGE onto the stack of previously-visited pages,
497 unless NO-HISTORY is non-nil."
498   (elpher-save-pos)
499   (elpher-process-cleanup)
500   (unless (or no-history
501               (equal (elpher-page-address elpher-current-page)
502                      (elpher-page-address page)))
503     (push elpher-current-page elpher-history))
504   (setq-local elpher-current-page page)
505   (let* ((address (elpher-page-address page))
506          (type (elpher-address-type address))
507          (type-record (cdr (assoc type elpher-type-map))))
508     (if type-record
509         (funcall (car type-record)
510                  (if renderer
511                      renderer
512                    (cadr type-record)))
513       (elpher-visit-previous-page)
514       (pcase type
515         (`(gopher ,type-char)
516          (error "Unsupported gopher selector type '%c' for '%s'"
517                 type-char (elpher-address-to-url address)))
518         (other
519          (error "Unsupported address type '%S' for '%s'"
520                 other (elpher-address-to-url address)))))))
521
522 (defun elpher-visit-previous-page ()
523   "Visit the previous page in the history."
524   (let ((previous-page (pop elpher-history)))
525     (if previous-page
526         (elpher-visit-page previous-page nil t)
527       (error "No previous page"))))
528
529 (defun elpher-reload-current-page ()
530   "Reload the current page, discarding any existing cached content."
531   (elpher-cache-content (elpher-page-address elpher-current-page) nil)
532   (elpher-visit-page elpher-current-page))
533
534 (defun elpher-save-pos ()
535   "Save the current position of point to the current page."
536   (when elpher-current-page
537     (elpher-cache-pos (elpher-page-address elpher-current-page) (point))))
538
539 (defun elpher-restore-pos ()
540   "Restore the position of point to that cached in the current page."
541   (let ((pos (elpher-get-cached-pos (elpher-page-address elpher-current-page))))
542     (if pos
543         (goto-char pos)
544       (goto-char (point-min)))))
545
546
547 ;;; Buffer preparation
548 ;;
549
550 (defvar elpher-buffer-name "*elpher*"
551   "The default name of the Elpher buffer.")
552
553 (defun elpher-update-header ()
554   "If `elpher-use-header' is true, display current page info in window header."
555   (if elpher-use-header
556       (let* ((display-string (elpher-page-display-string elpher-current-page))
557              (address (elpher-page-address elpher-current-page))
558              (tls-string (if (and (not (elpher-address-special-p address))
559                                   (member (elpher-address-protocol address)
560                                           '("gophers" "gemini")))
561                              " [TLS encryption]"
562                            ""))
563              (header (concat display-string
564                              (propertize tls-string 'face 'bold))))
565         (setq header-line-format header))))
566
567 (defmacro elpher-with-clean-buffer (&rest args)
568   "Evaluate ARGS with a clean *elpher* buffer as current."
569   `(with-current-buffer elpher-buffer-name
570      (unless (eq major-mode 'elpher-mode)
571        ;; avoid resetting buffer-local variables
572        (elpher-mode))
573      (let ((inhibit-read-only t))
574        (setq-local network-security-level
575                    (default-value 'network-security-level))
576        (erase-buffer)
577        (elpher-update-header)
578        ,@args)))
579
580 (defun elpher-buffer-message (string &optional line)
581   "Replace first line in elpher buffer with STRING.
582 If LINE is non-nil, replace that line instead."
583   (with-current-buffer elpher-buffer-name
584     (let ((inhibit-read-only t))
585       (goto-char (point-min))
586       (if line
587           (forward-line line))
588       (let ((data (match-data)))
589         (unwind-protect
590             (progn
591               (re-search-forward "^.*$")
592               (replace-match string))
593           (set-match-data data))))))
594
595
596 ;;; Text Processing
597 ;;
598
599 (defvar elpher-user-coding-system nil
600   "User-specified coding system to use for decoding text responses.")
601
602 (defun elpher-decode (string)
603   "Decode STRING using autodetected or user-specified coding system."
604   (decode-coding-string string
605                         (if elpher-user-coding-system
606                             elpher-user-coding-system
607                           (detect-coding-string string t))))
608
609 (defun elpher-preprocess-text-response (string)
610   "Preprocess text selector response contained in STRING.
611 This involes decoding the character representation, and clearing
612 away CRs and any terminating period."
613   (elpher-decode (replace-regexp-in-string "\n\.\n$" "\n"
614                                            (replace-regexp-in-string "\r" "" string))))
615
616
617 ;;; Network error reporting
618 ;;
619
620 (defun elpher-network-error (address error)
621   "Display ERROR message following unsuccessful negotiation with ADDRESS.
622 ERROR can be either an error object or a string."
623   (elpher-with-clean-buffer
624    (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
625            "When attempting to retrieve " (elpher-address-to-url address) ":\n"
626            (if (stringp error) error (error-message-string error)) "\n"
627            (propertize "\n----------------\n\n" 'face 'error)
628            "Press 'u' to return to the previous page.")))
629
630
631 ;;; General network communication
632 ;;
633
634 (defvar elpher-network-timer nil
635   "Timer used for network connections.")
636
637 (defvar elpher-use-tls nil
638   "If non-nil, use TLS to communicate with gopher servers.")
639
640 (defvar elpher-client-certificate nil
641   "If non-nil, contains client certificate details to use for TLS connections.")
642
643 (defun elpher-process-cleanup ()
644   "Immediately shut down any extant elpher process and timers."
645   (let ((p (get-process "elpher-process")))
646     (if p (delete-process p)))
647   (if (timerp elpher-network-timer)
648       (cancel-timer elpher-network-timer)))
649
650 (defun elpher-get-host-response (address default-port query-string response-processor
651                                          &optional use-tls force-ipv4)
652   "Generic function for retrieving data from ADDRESS.
653
654 When ADDRESS lacks a specific port, DEFAULT-PORT is used instead.
655 QUERY-STRING is a string sent to the host specified by ADDRESS to
656 illicet a response.  This response is passed as an argument to the
657 function RESPONSE-PROCESSOR.
658
659 If non-nil, USE-TLS specifies that the connection is to be made over
660 TLS.  If set to gemini, the certificate verification will be disabled
661 unless `elpher-gemini-TLS-cert-checks' is non-nil.
662
663 If non-nil, FORCE-IPV4 causes the network connection to be made over
664 ipv4 only.  (The default behaviour when this is not set depends on
665 the host operating system and the local network capabilities."
666   (if (and use-tls (not (gnutls-available-p)))
667       (error "Use of TLS requires Emacs to be compiled with GNU TLS support")
668     (unless (< (elpher-address-port address) 65536)
669       (error "Cannot establish network connection: port number > 65536"))
670     (when (and (eq use-tls 'gemini) (not elpher-gemini-TLS-cert-checks))
671       (setq-local network-security-level 'low)
672       (setq-local gnutls-verify-error nil))
673     (condition-case nil
674         (let* ((kill-buffer-query-functions nil)
675                (port (elpher-address-port address))
676                (service (if (> port 0) port default-port))
677                (host (elpher-address-host address))
678                (socks (or elpher-socks-always (string-suffix-p ".onion" host)))
679                (response-string-parts nil)
680                (bytes-received 0)
681                (hkbytes-received 0)
682                (timer (run-at-time elpher-connection-timeout nil
683                                    (lambda ()
684                                      (elpher-process-cleanup)
685                                      (cond
686                                         ; Try again with IPv4
687                                       ((not (or force-ipv4 socks))
688                                        (message "Connection timed out.  Retrying with IPv4.")
689                                        (elpher-get-host-response address default-port
690                                                                  query-string
691                                                                  response-processor
692                                                                  use-tls t))
693                                       ((and use-tls
694                                             (not (eq use-tls 'gemini))
695                                             (or elpher-auto-disengage-TLS
696                                                 (y-or-n-p
697                                                  "TLS connetion failed.  Disable TLS mode and retry? ")))
698                                        (setq elpher-use-tls nil)
699                                        (elpher-get-host-response address default-port
700                                                                  query-string
701                                                                  response-processor
702                                                                  nil force-ipv4))
703                                       (t
704                                        (elpher-network-error address "Connection time-out."))))))
705                (gnutls-params (list :type 'gnutls-x509pki :hostname host
706                                     :keylist (elpher-get-current-keylist address)))
707                (proc (if socks (socks-open-network-stream "elpher-process" nil host service)
708                        (make-network-process :name "elpher-process"
709                                              :host host
710                                              :family (and force-ipv4 'ipv4)
711                                              :service service
712                                              :buffer nil
713                                              :nowait t
714                                              :tls-parameters
715                                              (and use-tls
716                                                   (cons 'gnutls-x509pki
717                                                         (apply #'gnutls-boot-parameters
718                                                                gnutls-params)))))))
719           (setq elpher-network-timer timer)
720           (set-process-coding-system proc 'binary 'binary)
721           (set-process-query-on-exit-flag proc nil)
722           (elpher-buffer-message (concat "Connecting to " host "..."
723                                          " (press 'u' to abort)"))
724           (set-process-filter proc
725                               (lambda (_proc string)
726                                 (when timer
727                                   (cancel-timer timer)
728                                   (setq timer nil))
729                                 (setq bytes-received (+ bytes-received (length string)))
730                                 (let ((new-hkbytes-received (/ bytes-received 102400)))
731                                   (when (> new-hkbytes-received hkbytes-received)
732                                     (setq hkbytes-received new-hkbytes-received)
733                                     (elpher-buffer-message
734                                         (concat "("
735                                                 (number-to-string (/ hkbytes-received 10.0))
736                                                 " MB read)")
737                                         1)))
738                                 (setq response-string-parts
739                                       (cons string response-string-parts))))
740           (set-process-sentinel proc
741                                 (lambda (proc event)
742                                   (when timer
743                                     (cancel-timer timer))
744                                   (condition-case the-error
745                                       (cond
746                                        ((string-prefix-p "open" event)    ; request URL
747                                         (elpher-buffer-message
748                                          (concat "Connected to " host ". Receiving data..."
749                                                  " (press 'u' to abort)"))
750                                         (let ((inhibit-eol-conversion t))
751                                           (process-send-string proc query-string)))
752                                        ((string-prefix-p "deleted" event)) ; do nothing
753                                        ((and (not response-string-parts)
754                                              (not (or elpher-ipv4-always force-ipv4 socks)))
755                                         ; Try again with IPv4
756                                         (message "Connection failed. Retrying with IPv4.")
757                                         (elpher-get-host-response address default-port
758                                                                   query-string
759                                                                   response-processor
760                                                                   use-tls t))
761                                        (response-string-parts
762                                         (elpher-with-clean-buffer
763                                          (insert "Data received.  Rendering..."))
764                                         (funcall response-processor
765                                                  (apply #'concat (reverse response-string-parts)))
766                                         (elpher-restore-pos))
767                                        (t
768                                         (error "No response from server")))
769                                     (error
770                                      (elpher-network-error address the-error)))))
771           (when socks
772             (if use-tls (apply #'gnutls-negotiate :process proc gnutls-params))
773             (funcall (process-sentinel proc) proc "open\n")))
774       (error
775        (error "Error initiating connection to server")))))
776
777
778 ;;; Client-side TLS Certificate Management
779 ;;
780
781 (defun elpher-generate-certificate (common-name key-file cert-file &optional temporary)
782   "Generate a key and a self-signed client TLS certificate using openssl.
783
784 The Common Name field of the certificate is set to COMMON-NAME.  The
785 arguments KEY-FILE and CERT-FILE should contain the absolute paths of
786 the key and certificate files to write.
787
788 If TEMPORARY is non-nil, the certificate will be given an exporation
789 period of one day, and the key and certificate files will be deleted
790 when the certificate is no longer needed for the current session.
791
792 Otherwise, the certificate will be given a 100 year expiration period
793 and the files will not be deleted.
794
795 The function returns a list containing the current host name, the
796 temporary flag, and the key and cert file names in the form required
797 by `gnutls-boot-parameters`."
798   (let ((exp-key-file (expand-file-name key-file))
799         (exp-cert-file (expand-file-name cert-file)))
800     (condition-case nil
801         (progn
802           (call-process elpher-openssl-command nil nil nil
803                         "req" "-x509" "-newkey" "rsa:2048"
804                         "-days" (if temporary "1" "36500")
805                         "-nodes"
806                         "-subj" (concat "/CN=" common-name)
807                         "-keyout" exp-key-file
808                         "-out" exp-cert-file)
809           (list (elpher-address-host (elpher-page-address elpher-current-page))
810                 temporary exp-key-file exp-cert-file))
811       (error
812        (message "Check that openssl is installed, or customize `elpher-openssl-command`.")
813        (error "Program 'openssl', required for certificate generation, not found")))))
814
815 (defun elpher-generate-throwaway-certificate ()
816   "Generate and return details of a throwaway certificate.
817 The key and certificate files will be deleted when they are no
818 longer needed for this session."
819   (let* ((file-base (make-temp-name "elpher"))
820          (key-file (concat temporary-file-directory file-base ".key"))
821          (cert-file (concat temporary-file-directory file-base ".crt")))
822     (elpher-generate-certificate file-base key-file cert-file t)))
823
824 (defun elpher-generate-persistent-certificate (file-base common-name)
825   "Generate and return details of a persistent certificate.
826 The argument FILE-BASE is used as the base for the key and certificate
827 files, while COMMON-NAME specifies the common name field of the
828 certificate.
829
830 The key and certificate files are written to in `elpher-certificate-directory'."
831   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
832          (cert-file (concat elpher-certificate-directory file-base ".crt")))
833     (elpher-generate-certificate common-name key-file cert-file)))
834
835 (defun elpher-get-existing-certificate (file-base)
836   "Return a certificate object corresponding to an existing certificate.
837 It is assumed that the key files FILE-BASE.key and FILE-BASE.crt exist in
838 the directory `elpher-certificate-directory'."
839   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
840          (cert-file (concat elpher-certificate-directory file-base ".crt")))
841     (list (elpher-address-host (elpher-page-address elpher-current-page))
842           nil
843           (expand-file-name key-file)
844           (expand-file-name cert-file))))
845
846 (defun elpher-install-and-use-existing-certificate (key-file-src cert-file-src file-base)
847   "Install a key+certificate file pair in `elpher-certificate-directory'.
848 The strings KEY-FILE-SRC and CERT-FILE-SRC are the existing key and
849 certificate files to install.  The argument FILE-BASE is used as the
850 base for the installed key and certificate files."
851   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
852          (cert-file (concat elpher-certificate-directory file-base ".crt")))
853     (if (or (file-exists-p key-file)
854             (file-exists-p cert-file))
855         (error "A certificate with base name %s is already installed" file-base))
856     (copy-file key-file-src key-file)
857     (copy-file cert-file-src cert-file)
858     (list (elpher-address-host (elpher-page-address elpher-current-page))
859           nil
860           (expand-file-name key-file)
861           (expand-file-name cert-file))))
862
863 (defun elpher-list-existing-certificates ()
864   "Return a list of the persistent certificates in `elpher-certificate-directory'."
865   (unless (file-directory-p elpher-certificate-directory)
866     (make-directory elpher-certificate-directory))
867   (mapcar
868    (lambda (file)
869      (file-name-sans-extension file))
870    (directory-files elpher-certificate-directory nil "\\.key$")))
871
872 (defun elpher-forget-current-certificate ()
873   "Causes any current certificate to be forgotten.)
874 In the case of throwaway certificates, the key and certificate files
875 are also deleted."
876   (interactive)
877   (when elpher-client-certificate
878     (unless (and (called-interactively-p 'any)
879                  (not (y-or-n-p (concat "Really forget client certificate? "
880                                         "(Throwaway certificates will be deleted.)"))))
881       (when (cadr elpher-client-certificate)
882         (delete-file (elt elpher-client-certificate 2))
883         (delete-file (elt elpher-client-certificate 3)))
884       (setq elpher-client-certificate nil)
885       (if (called-interactively-p 'any)
886           (message "Client certificate forgotten.")))))
887
888 (defun elpher-get-current-keylist (address)
889   "Retrieve the `gnutls-boot-parameters'-compatable keylist.
890
891 This is obtained from the client certificate described by
892 `elpher-current-certificate', if one is available and the host for
893 that certificate matches the host in ADDRESS.
894
895 If `elpher-current-certificate' is non-nil, and its host name doesn't
896 match that of ADDRESS, the certificate is forgotten."
897   (if elpher-client-certificate
898       (if (string= (car elpher-client-certificate)
899                    (elpher-address-host address))
900           (list (cddr elpher-client-certificate))
901         (elpher-forget-current-certificate)
902         (message "Disabling client certificate for new host")
903         nil)
904     nil))
905
906
907 ;;; Gopher selector retrieval
908 ;;
909
910 (defun elpher-get-gopher-response (address renderer)
911   "Get response string from gopher server at ADDRESS and render using RENDERER."
912   (elpher-get-host-response address 70
913                             (concat (elpher-gopher-address-selector address) "\r\n")
914                             renderer
915                             (or (string= (elpher-address-protocol address) "gophers")
916                                 elpher-use-tls)))
917
918 (defun elpher-get-gopher-page (renderer)
919   "Getter function for gopher pages.
920 The RENDERER procedure is used to display the contents of the page
921 once they are retrieved from the gopher server."
922   (let* ((address (elpher-page-address elpher-current-page))
923          (content (elpher-get-cached-content address)))
924     (if (and content (funcall renderer nil))
925         (elpher-with-clean-buffer
926          (insert content)
927          (elpher-restore-pos))
928       (elpher-with-clean-buffer
929        (insert "LOADING... (use 'u' to cancel)\n"))
930       (condition-case the-error
931           (elpher-get-gopher-response address renderer)
932         (error
933          (elpher-network-error address the-error))))))
934
935 ;; Index rendering
936
937 (defun elpher-insert-index (string)
938   "Insert the index corresponding to STRING into the current buffer."
939   ;; Should be able to split directly on CRLF, but some non-conformant
940   ;; LF-only servers sadly exist, hence the following.
941   (let ((str-processed (elpher-preprocess-text-response string)))
942     (dolist (line (split-string str-processed "\n"))
943       (ignore-errors
944         (unless (= (length line) 0)
945           (let* ((type (elt line 0))
946                  (fields (split-string (substring line 1) "\t"))
947                  (display-string (elt fields 0))
948                  (selector (elt fields 1))
949                  (host (elt fields 2))
950                  (port (if (elt fields 3)
951                            (string-to-number (elt fields 3))
952                          nil))
953                  (address (elpher-make-gopher-address type selector host port)))
954             (elpher-insert-index-record display-string address)))))))
955
956 (defun elpher-insert-margin (&optional type-name)
957   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
958   (if type-name
959       (progn
960         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
961                         (concat
962                          (propertize "[" 'face 'elpher-margin-brackets)
963                          (propertize type-name 'face 'elpher-margin-key)
964                          (propertize "]" 'face 'elpher-margin-brackets))))
965         (insert " "))
966     (insert (make-string elpher-margin-width ?\s))))
967
968 (defun elpher--page-button-help (_window buffer pos)
969   "Function called by Emacs to generate mouse-over text.
970 The arguments specify the BUFFER and the POS within the buffer of the item
971 for which help is required.  The function returns the help to be
972 displayed.  The _WINDOW argument is currently unused."
973   (with-current-buffer buffer
974     (let ((button (button-at pos)))
975       (when button
976         (let* ((page (button-get button 'elpher-page))
977                (address (elpher-page-address page)))
978           (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
979                                                 address
980                                               (elpher-address-to-url address))))))))
981
982 (defun elpher-insert-index-record (display-string &optional address)
983   "Function to insert an index record into the current buffer.
984 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
985 If ADDRESS is not supplied or nil the record is rendered as an
986 'information' line."
987   (let* ((type (if address (elpher-address-type address) nil))
988          (type-map-entry (cdr (assoc type elpher-type-map))))
989     (if type-map-entry
990         (let* ((margin-code (elt type-map-entry 2))
991                (face (elt type-map-entry 3))
992                (filtered-display-string (elpher-color-filter-apply display-string))
993                (page (elpher-make-page filtered-display-string address)))
994           (elpher-insert-margin margin-code)
995           (insert-text-button filtered-display-string
996                               'face face
997                               'elpher-page page
998                               'action #'elpher-click-link
999                               'follow-link t
1000                               'help-echo #'elpher--page-button-help))
1001       (pcase type
1002         ('nil ;; Information
1003          (elpher-insert-margin)
1004          (let ((propertized-display-string
1005                 (propertize display-string 'face 'elpher-info)))
1006            (insert (elpher-process-text-for-display propertized-display-string))))
1007         (`(gopher ,selector-type) ;; Unknown
1008          (elpher-insert-margin (concat (char-to-string selector-type) "?"))
1009          (insert (propertize display-string
1010                              'face 'elpher-unknown)))))
1011     (insert "\n")))
1012
1013 (defun elpher-click-link (button)
1014   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
1015   (let ((page (button-get button 'elpher-page)))
1016     (elpher-visit-page page)))
1017
1018 (defun elpher-render-index (data &optional _mime-type-string)
1019   "Render DATA as an index.  MIME-TYPE-STRING is unused."
1020   (elpher-with-clean-buffer
1021    (if (not data)
1022        t
1023      (elpher-insert-index data)
1024      (elpher-cache-content (elpher-page-address elpher-current-page)
1025                            (buffer-string)))))
1026
1027 ;; Text rendering
1028
1029 (defconst elpher-url-regex
1030   "\\([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\-_~?/@|#]\\)?\\)?"
1031   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
1032
1033 (defun elpher-buttonify-urls (string)
1034   "Turn substrings which look like urls in STRING into clickable buttons."
1035   (with-temp-buffer
1036     (insert string)
1037     (goto-char (point-min))
1038     (while (re-search-forward elpher-url-regex nil t)
1039       (let ((page (elpher-make-page (substring-no-properties (match-string 0))
1040                                     (elpher-address-from-url (match-string 0)))))
1041           (make-text-button (match-beginning 0)
1042                             (match-end 0)
1043                             'elpher-page  page
1044                             'action #'elpher-click-link
1045                             'follow-link t
1046                             'help-echo #'elpher--page-button-help
1047                             'face 'button)))
1048     (buffer-string)))
1049
1050 (defconst elpher-ansi-regex "\x1b\\[[^m]*m"
1051   "Wildly incomplete regexp used to strip out some troublesome ANSI escape sequences.")
1052
1053 (defun elpher-process-text-for-display (string)
1054   "Perform any desired processing of STRING prior to display as text.
1055 Currently includes buttonifying URLs and processing ANSI escape codes."
1056   (elpher-buttonify-urls (if elpher-filter-ansi-from-text
1057                              (elpher-color-filter-apply string)
1058                            (elpher-color-apply string))))
1059
1060 (defun elpher-render-text (data &optional _mime-type-string)
1061   "Render DATA as text.  MIME-TYPE-STRING is unused."
1062   (elpher-with-clean-buffer
1063    (if (not data)
1064        t
1065      (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
1066      (elpher-cache-content
1067       (elpher-page-address elpher-current-page)
1068       (buffer-string)))))
1069
1070 ;; Image retrieval
1071
1072 (defun elpher-render-image (data &optional _mime-type-string)
1073   "Display DATA as image.  MIME-TYPE-STRING is unused."
1074   (if (not data)
1075       nil
1076     (if (display-images-p)
1077         (progn
1078           (let ((image (create-image
1079                         data
1080                         nil t)))
1081             (elpher-with-clean-buffer
1082              (insert-image image)
1083              (elpher-restore-pos))))
1084       (elpher-render-download data))))
1085
1086 ;; Search retrieval and rendering
1087
1088 (defun elpher-get-gopher-query-page (renderer)
1089   "Getter for gopher addresses requiring input.
1090 The response is rendered using the rendering function RENDERER."
1091    (let* ((address (elpher-page-address elpher-current-page))
1092           (content (elpher-get-cached-content address))
1093           (aborted t))
1094     (if (and content (funcall renderer nil))
1095         (elpher-with-clean-buffer
1096          (insert content)
1097          (elpher-restore-pos)
1098          (message "Displaying cached search results.  Reload to perform a new search."))
1099       (unwind-protect
1100           (let* ((query-string (read-string "Query: "))
1101                  (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
1102                  (search-address (elpher-make-gopher-address ?1
1103                                                              query-selector
1104                                                              (elpher-address-host address)
1105                                                              (elpher-address-port address)
1106                                                              (equal (elpher-address-type address) "gophers"))))
1107             (setq aborted nil)
1108
1109             (elpher-with-clean-buffer
1110              (insert "LOADING RESULTS... (use 'u' to cancel)"))
1111             (elpher-get-gopher-response search-address renderer))
1112         (if aborted
1113             (elpher-visit-previous-page))))))
1114
1115 ;; Raw server response rendering
1116
1117 (defun elpher-render-raw (data &optional mime-type-string)
1118   "Display raw DATA in buffer.  MIME-TYPE-STRING is also displayed if provided."
1119   (if (not data)
1120       nil
1121     (elpher-with-clean-buffer
1122      (when mime-type-string
1123        (insert "MIME type specified by server: '" mime-type-string "'\n"))
1124      (insert data)
1125      (goto-char (point-min)))
1126     (message "Displaying raw server response.  Reload or redraw to return to standard view.")))
1127
1128 ;; File save "rendering"
1129
1130 (defun elpher-render-download (data &optional _mime-type-string)
1131   "Save DATA to file.  MIME-TYPE-STRING is unused."
1132   (if (not data)
1133       nil
1134     (let* ((address (elpher-page-address elpher-current-page))
1135            (selector (if (elpher-address-gopher-p address)
1136                          (elpher-gopher-address-selector address)
1137                        (elpher-address-filename address))))
1138       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1139       (let* ((filename-proposal (file-name-nondirectory selector))
1140              (filename (read-file-name "Download complete. Save file as: "
1141                                        nil nil nil
1142                                        (if (> (length filename-proposal) 0)
1143                                            filename-proposal
1144                                          "download.file"))))
1145         (let ((coding-system-for-write 'binary))
1146           (with-temp-file filename
1147             (insert data)))
1148         (message (format "Saved to file %s." filename))))))
1149
1150 ;; HTML rendering
1151
1152 (defun elpher-render-html (data &optional _mime-type-string)
1153   "Render DATA as HTML using shr.  MIME-TYPE-STRING is unused."
1154   (elpher-with-clean-buffer
1155    (if (not data)
1156        t
1157      (let ((dom (with-temp-buffer
1158                   (insert data)
1159                   (libxml-parse-html-region (point-min) (point-max)))))
1160        (shr-insert-document dom)))))
1161
1162 ;; Gemini page retrieval
1163
1164 (defvar elpher-gemini-redirect-chain)
1165
1166 (defun elpher-get-gemini-response (address renderer)
1167   "Get response string from gemini server at ADDRESS and render using RENDERER."
1168   (elpher-get-host-response address 1965
1169                             (concat (elpher-address-to-url address) "\r\n")
1170                             (lambda (response-string)
1171                               (elpher-process-gemini-response response-string renderer))
1172                             'gemini))
1173
1174 (defun elpher-parse-gemini-response (response)
1175   "Parse the RESPONSE string and return a list of components.
1176 The list is of the form (code meta body).  A response of nil implies
1177 that the response was malformed."
1178   (let ((header-end-idx (string-match "\r\n" response)))
1179     (if header-end-idx
1180         (let ((header (string-trim (substring response 0 header-end-idx)))
1181               (body (substring response (+ header-end-idx 2))))
1182           (if (>= (length header) 2)
1183               (let ((code (substring header 0 2))
1184                     (meta (string-trim (substring header 2))))
1185                 (list code meta body))
1186             (error "Malformed response: No response status found in header %s" header)))
1187       (error "Malformed response: No CRLF-delimited header found in response %s" response))))
1188
1189 (defun elpher-process-gemini-response (response-string renderer)
1190   "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
1191   (let ((response-components (elpher-parse-gemini-response response-string)))
1192     (let ((response-code (elt response-components 0))
1193           (response-meta (elt response-components 1))
1194           (response-body (elt response-components 2)))
1195       (pcase (elt response-code 0)
1196         (?1 ; Input required
1197          (elpher-with-clean-buffer
1198           (insert "Gemini server is requesting input."))
1199          (let* ((query-string
1200                  (if (eq (elt response-code 1) ?1)
1201                      (read-passwd (concat response-meta ": "))
1202                    (read-string (concat response-meta ": "))))
1203                 (query-address (seq-copy (elpher-page-address elpher-current-page)))
1204                 (old-fname (url-filename query-address)))
1205            (setf (url-filename query-address)
1206                  (concat old-fname "?" (url-build-query-string `((,query-string)))))
1207            (elpher-get-gemini-response query-address renderer)))
1208         (?2 ; Normal response
1209          (funcall renderer response-body response-meta))
1210         (?3 ; Redirect
1211          (message "Following redirect to %s" response-meta)
1212          (if (>= (length elpher-gemini-redirect-chain) 5)
1213              (error "More than 5 consecutive redirects followed"))
1214          (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
1215            (if (member redirect-address elpher-gemini-redirect-chain)
1216                (error "Redirect loop detected"))
1217            (if (not (string= (elpher-address-protocol redirect-address)
1218                              "gemini"))
1219                (error "Server tried to automatically redirect to non-gemini URL: %s"
1220                       response-meta))
1221            (elpher-page-set-address elpher-current-page redirect-address)
1222            (add-to-list 'elpher-gemini-redirect-chain redirect-address)
1223            (elpher-get-gemini-response redirect-address renderer)))
1224         (?4 ; Temporary failure
1225          (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
1226                 response-code response-meta))
1227         (?5 ; Permanent failure
1228          (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
1229                 response-code response-meta))
1230         (?6 ; Client certificate required
1231          (elpher-with-clean-buffer
1232           (if elpher-client-certificate
1233               (insert "Gemini server does not recognise the provided TLS certificate:\n\n")
1234             (insert "Gemini server is requesting a valid TLS certificate:\n\n"))
1235           (auto-fill-mode 1)
1236           (elpher-gemini-insert-text response-meta))
1237          (let ((chosen-certificate (elpher-choose-client-certificate)))
1238            (unless chosen-certificate
1239              (error "Gemini server requires a client certificate and none was provided"))
1240            (setq elpher-client-certificate chosen-certificate))
1241          (elpher-with-clean-buffer)
1242          (elpher-get-gemini-response (elpher-page-address elpher-current-page) renderer))
1243         (_other
1244          (error "Gemini server response unknown: %s %s"
1245                 response-code response-meta))))))
1246
1247 (defun elpher-choose-client-certificate ()
1248   "Prompt for a client certificate to use to establish a TLS connection."
1249   (let* ((read-answer-short t))
1250     (pcase (read-answer "What do you want to do? "
1251                         '(("throwaway" ?t
1252                            "generate and use throw-away certificate")
1253                           ("persistent" ?p
1254                            "generate new or use existing persistent certificate")
1255                           ("abort" ?a
1256                            "stop immediately")))
1257       ("throwaway"
1258        (setq elpher-client-certificate (elpher-generate-throwaway-certificate)))
1259       ("persistent"
1260        (let* ((existing-certificates (elpher-list-existing-certificates))
1261               (file-base (completing-read
1262                           "Nickname for new or existing certificate (autocompletes, empty response aborts): "
1263                           existing-certificates)))
1264          (if (string-empty-p (string-trim file-base))
1265              nil
1266            (if (member file-base existing-certificates)
1267                (setq elpher-client-certificate
1268                      (elpher-get-existing-certificate file-base))
1269              (pcase (read-answer "Generate new certificate or install externally-generated one? "
1270                                  '(("new" ?n
1271                                     "generate new certificate")
1272                                    ("install" ?i
1273                                     "install existing certificate")
1274                                    ("abort" ?a
1275                                     "stop immediately")))
1276                ("new"
1277                 (let ((common-name (read-string "Common Name field for new certificate: "
1278                                                 file-base)))
1279                   (message "New key and self-signed certificate written to %s"
1280                            elpher-certificate-directory)
1281                   (elpher-generate-persistent-certificate file-base common-name)))
1282                ("install"
1283                 (let* ((cert-file (read-file-name "Certificate file: " nil nil t))
1284                        (key-file (read-file-name "Key file: " nil nil t)))
1285                   (message "Key and certificate installed in %s for future use"
1286                            elpher-certificate-directory)
1287                   (elpher-install-and-use-existing-certificate key-file
1288                                                                cert-file
1289                                                                file-base)))
1290                ("abort" nil))))))
1291       ("abort" nil))))
1292
1293 (defun elpher-get-gemini-page (renderer)
1294   "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1295   (let* ((address (elpher-page-address elpher-current-page))
1296          (content (elpher-get-cached-content address)))
1297     (condition-case the-error
1298         (if (and content (funcall renderer nil))
1299             (elpher-with-clean-buffer
1300               (insert content)
1301               (elpher-restore-pos))
1302           (elpher-with-clean-buffer
1303            (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1304           (setq elpher-gemini-redirect-chain nil)
1305           (elpher-get-gemini-response address renderer))
1306       (error
1307        (elpher-network-error address the-error)))))
1308
1309 (defun elpher-render-gemini (body &optional mime-type-string)
1310   "Render gemini response BODY with rendering MIME-TYPE-STRING."
1311   (if (not body)
1312       t
1313     (let* ((mime-type-string* (if (or (not mime-type-string)
1314                                       (string-empty-p mime-type-string))
1315                                   "text/gemini; charset=utf-8"
1316                                 mime-type-string))
1317            (mime-type-split (split-string mime-type-string* ";" t))
1318            (mime-type (string-trim (car mime-type-split)))
1319            (parameters (mapcar (lambda (s)
1320                                  (let ((key-val (split-string s "=")))
1321                                    (list (downcase (string-trim (car key-val)))
1322                                          (downcase (string-trim (cadr key-val))))))
1323                                (cdr mime-type-split))))
1324       (when (string-prefix-p "text/" mime-type)
1325         (setq body (decode-coding-string
1326                     body
1327                     (if (assoc "charset" parameters)
1328                         (intern (cadr (assoc "charset" parameters)))
1329                       'utf-8)))
1330         (setq body (replace-regexp-in-string "\r" "" body)))
1331       (pcase mime-type
1332         ((or "text/gemini" "")
1333          (elpher-render-gemini-map body parameters))
1334         ("text/html"
1335          (elpher-render-html body))
1336         ((pred (string-prefix-p "text/"))
1337          (elpher-render-gemini-plain-text body parameters))
1338         ((pred (string-prefix-p "image/"))
1339          (elpher-render-image body))
1340         (_other
1341          (elpher-render-download body))))))
1342
1343 (defun elpher-gemini-get-link-url (link-line)
1344   "Extract the url portion of LINK-LINE, a gemini map file link line.
1345 Returns nil in the event that the contents of the line following the
1346 => prefix are empty."
1347   (let ((l (split-string (substring link-line 2))))
1348     (if l
1349         (string-trim (elt l 0))
1350       nil)))
1351
1352 (defun elpher-gemini-get-link-display-string (link-line)
1353   "Extract the display string portion of LINK-LINE, a gemini map file link line.
1354 Returns the url portion in the event that the display-string portion is empty."
1355   (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1356          (idx (string-match "[ \t]" rest)))
1357     (string-trim (if idx
1358                      (substring rest (+ idx 1))
1359                    rest))))
1360
1361 (defun elpher-collapse-dot-sequences (filename)
1362   "Collapse dot sequences in FILENAME.
1363 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1364   (let* ((path (split-string filename "/"))
1365          (path-reversed-normalized
1366           (seq-reduce (lambda (a b)
1367                         (cond ((and a (equal b "..") (cdr a)))
1368                               ((and (not a) (equal b "..")) a) ;leading .. are dropped
1369                               ((equal b ".") a)
1370                               (t (cons b a))))
1371                       path nil)))
1372     (string-join (reverse path-reversed-normalized) "/")))
1373
1374 (defun elpher-address-from-gemini-url (url)
1375   "Extract address from URL with defaults as per gemini map files.
1376 While there's obviously some redundancy here between this function and
1377 `elpher-address-from-url', gemini map file URLs require enough special
1378 treatment that a separate function is warranted."
1379   (let ((address (url-generic-parse-url url))
1380         (current-address (elpher-page-address elpher-current-page)))
1381     (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1382       (setf (url-fullness address) t)
1383       (if (url-host address) ;if there is an explicit host, filenames are absolute
1384           (if (string-empty-p (url-filename address))
1385               (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1386         (setf (url-host address) (url-host current-address))
1387         (setf (url-port address) (url-port current-address))
1388         (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1389           (setf (url-filename address)
1390                 (concat (file-name-directory (url-filename current-address))
1391                         (url-filename address)))))
1392       (unless (url-type address)
1393         (setf (url-type address) "gemini"))
1394       (when (equal (url-type address) "gemini")
1395         (setf (url-filename address)
1396               (elpher-collapse-dot-sequences (url-filename address)))))
1397     (elpher-remove-redundant-ports address)))
1398
1399 (defun elpher-gemini-insert-link (link-line)
1400   "Insert link described by LINK-LINE into a text/gemini document."
1401   (let* ((url (elpher-gemini-get-link-url link-line))
1402          (display-string (elpher-gemini-get-link-display-string link-line))
1403          (address (elpher-address-from-gemini-url url))
1404          (type (if address (elpher-address-type address) nil))
1405          (type-map-entry (cdr (assoc type elpher-type-map))))
1406     (when display-string
1407       (insert elpher-gemini-link-string)
1408       (if type-map-entry
1409           (let* ((face (elt type-map-entry 3))
1410                  (filtered-display-string (elpher-color-filter-apply display-string))
1411                  (page (elpher-make-page filtered-display-string address)))
1412             (insert-text-button filtered-display-string
1413                                 'face face
1414                                 'elpher-page page
1415                                 'action #'elpher-click-link
1416                                 'follow-link t
1417                                 'help-echo #'elpher--page-button-help))
1418         (insert (propertize display-string 'face 'elpher-unknown)))
1419       (insert "\n"))))
1420
1421 (defun elpher-gemini-insert-header (header-line)
1422   "Insert header described by HEADER-LINE into a text/gemini document.
1423 The gemini map file line describing the header is given
1424 by HEADER-LINE."
1425   (when (string-match "^\\(#+\\)[ \t]*" header-line)
1426     (let* ((level (length (match-string 1 header-line)))
1427            (header (substring header-line (match-end 0)))
1428            (face (pcase level
1429                    (1 'elpher-gemini-heading1)
1430                    (2 'elpher-gemini-heading2)
1431                    (3 'elpher-gemini-heading3)
1432                    (_ 'default)))
1433            (fill-column (if (display-graphic-p)
1434                             (/ (* fill-column
1435                                   (font-get (font-spec :name (face-font 'default)) :size))
1436                                (font-get (font-spec :name (face-font face)) :size)) fill-column)))
1437       (unless (display-graphic-p)
1438         (insert (make-string level ?#) " "))
1439       (insert (propertize header 'face face))
1440       (newline))))
1441
1442 (defun elpher-gemini-insert-text (text-line)
1443   "Insert a plain non-preformatted TEXT-LINE into a text/gemini document.
1444 This function uses Emacs' auto-fill to wrap text sensibly to a maximum
1445 width defined by elpher-gemini-max-fill-width."
1446   (string-match "\\(^[ \t]*\\)\\(\*[ \t]+\\|>[ \t]*\\)?" text-line)
1447   (let* ((line-prefix (match-string 2 text-line))
1448          (processed-text-line
1449           (if line-prefix
1450               (cond ((string-prefix-p "*" line-prefix)
1451                      (concat
1452                       (replace-regexp-in-string "\*"
1453                                                 elpher-gemini-bullet-string
1454                                                 (match-string 0 text-line))
1455                       (substring text-line (match-end 0))))
1456                     ((string-prefix-p ">" line-prefix)
1457                      (propertize text-line 'face 'elpher-gemini-quoted))
1458                     (t text-line))
1459             text-line))
1460          (adaptive-fill-mode nil))
1461     (insert (elpher-process-text-for-display processed-text-line))
1462     (newline)))
1463
1464 (defun elpher-render-gemini-map (data _parameters)
1465   "Render DATA as a gemini map file, PARAMETERS is currently unused."
1466   (elpher-with-clean-buffer
1467    (let ((preformatted nil))
1468      (auto-fill-mode 1)
1469      (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1470      (dolist (line (split-string data "\n"))
1471        (cond
1472         ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1473         (preformatted (insert (elpher-process-text-for-display
1474                                (propertize line 'face 'elpher-gemini-preformatted))
1475                               "\n"))
1476         ((string-prefix-p "=>" line) (elpher-gemini-insert-link line))
1477         ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1478         (t (elpher-gemini-insert-text line)))))
1479    (elpher-cache-content
1480     (elpher-page-address elpher-current-page)
1481     (buffer-string))))
1482
1483 (defun elpher-render-gemini-plain-text (data _parameters)
1484   "Render DATA as plain text file.  PARAMETERS is currently unused."
1485   (elpher-with-clean-buffer
1486    (insert (elpher-process-text-for-display data))
1487    (elpher-cache-content
1488     (elpher-page-address elpher-current-page)
1489     (buffer-string))))
1490
1491
1492 ;; Finger page connection
1493
1494 (defun elpher-get-finger-page (renderer)
1495   "Opens a finger connection to the current page address.
1496 The result is rendered using RENDERER."
1497   (let* ((address (elpher-page-address elpher-current-page))
1498          (content (elpher-get-cached-content address)))
1499     (if (and content (funcall renderer nil))
1500         (elpher-with-clean-buffer
1501          (insert content)
1502          (elpher-restore-pos))
1503       (elpher-with-clean-buffer
1504        (insert "LOADING... (use 'u' to cancel)\n"))
1505       (condition-case the-error
1506           (let* ((kill-buffer-query-functions nil)
1507                  (user (let ((filename (elpher-address-filename address)))
1508                          (if (> (length filename) 1)
1509                              (substring filename 1)
1510                            (elpher-address-user address)))))
1511             (elpher-get-host-response address 79
1512                                       (concat user "\r\n")
1513                                       renderer))
1514         (error
1515          (elpher-network-error address the-error))))))
1516
1517
1518 ;; Telnet page connection
1519
1520 (defun elpher-get-telnet-page (renderer)
1521   "Opens a telnet connection to the current page address (RENDERER must be nil)."
1522   (when renderer
1523     (elpher-visit-previous-page)
1524     (error "Command not supported for telnet URLs"))
1525   (let* ((address (elpher-page-address elpher-current-page))
1526          (host (elpher-address-host address))
1527          (port (elpher-address-port address)))
1528     (elpher-visit-previous-page)
1529     (if (> port 0)
1530         (telnet host port)
1531       (telnet host))))
1532
1533
1534 ;; Other URL page opening
1535
1536 (defun elpher-get-other-url-page (renderer)
1537   "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1538   (when renderer
1539     (elpher-visit-previous-page)
1540     (error "Command not supported for general URLs"))
1541   (let* ((address (elpher-page-address elpher-current-page))
1542          (url (elpher-address-to-url address)))
1543     (progn
1544       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1545       (message "Opening URL...")
1546       (if elpher-open-urls-with-eww
1547           (browse-web url)
1548         (browse-url url)))))
1549
1550
1551 ;; Start page page retrieval
1552
1553 (defun elpher-get-start-page (renderer)
1554   "Getter which displays the start page (RENDERER must be nil)."
1555   (when renderer
1556     (elpher-visit-previous-page)
1557     (error "Command not supported for start page"))
1558   (elpher-with-clean-buffer
1559    (insert "     --------------------------------------------\n"
1560            "           Elpher Gopher and Gemini Client       \n"
1561            "                   version " elpher-version "\n"
1562            "     --------------------------------------------\n"
1563            "\n"
1564            "Default bindings:\n"
1565            "\n"
1566            " - TAB/Shift-TAB: next/prev item on current page\n"
1567            " - RET/mouse-1: open item under cursor\n"
1568            " - m: select an item on current page by name (autocompletes)\n"
1569            " - u/mouse-3/U: return to previous page or to the start page\n"
1570            " - o/O: visit different selector or the root menu of the current server\n"
1571            " - g: go to a particular address (gopher, gemini, finger)\n"
1572            " - d/D: download item under cursor or current page\n"
1573            " - i/I: info on item under cursor or current page\n"
1574            " - c/C: copy URL representation of item under cursor or current page\n"
1575            " - a/A: bookmark the item under cursor or current page\n"
1576            " - x/X: remove bookmark for item under cursor or current page\n"
1577            " - B: visit the bookmarks page\n"
1578            " - r: redraw current page (using cached contents if available)\n"
1579            " - R: reload current page (regenerates cache)\n"
1580            " - S: set character coding system for gopher (default is to autodetect)\n"
1581            " - T: toggle TLS gopher mode\n"
1582            " - F: forget/discard current TLS client certificate\n"
1583            " - .: display the raw server response for the current page\n"
1584            "\n"
1585            "Start your exploration of gopher space and gemini:\n")
1586    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1587                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1588    (elpher-insert-index-record "Project Gemini home page"
1589                                (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1590    (insert "\n"
1591            "Alternatively, select a search engine and enter some search terms:\n")
1592    (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1593                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1594    (elpher-insert-index-record "Gemini Search Engine (GUS)"
1595                                (elpher-address-from-url "gemini://gus.guru/search"))
1596    (insert "\n"
1597            "This page contains your bookmarked sites (also visit with B):\n")
1598    (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1599    (insert "\n"
1600            "For Elpher release news or to leave feedback, visit:\n")
1601    (elpher-insert-index-record "The Elpher Project Page"
1602                                (elpher-make-gopher-address ?1
1603                                                            "/projects/elpher/"
1604                                                            "thelambdalab.xyz"
1605                                                            70))
1606    (insert "\n"
1607            "** Refer to the ")
1608    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1609      (insert-text-button "Elpher info manual"
1610                          'face 'link
1611                          'action (lambda (_)
1612                                    (interactive)
1613                                    (info "(elpher)"))
1614                          'follow-link t
1615                          'help-echo help-string))
1616    (insert " for the full documentation. **\n")
1617    (insert (propertize
1618             (concat "  (This should be available if you have installed Elpher using\n"
1619                     "   MELPA. Otherwise you will have to install the manual yourself.)\n")
1620             'face 'shadow))
1621    (elpher-restore-pos)))
1622
1623 ;; Bookmarks page page retrieval
1624
1625 (defun elpher-get-bookmarks-page (renderer)
1626   "Getter to load and display the current bookmark list (RENDERER must be nil)."
1627   (when renderer
1628     (elpher-visit-previous-page)
1629     (error "Command not supported for bookmarks page"))
1630   (elpher-with-clean-buffer
1631    (insert "---- Bookmark list ----\n\n")
1632    (let ((bookmarks (elpher-load-bookmarks)))
1633      (if bookmarks
1634          (dolist (bookmark bookmarks)
1635            (let ((display-string (elpher-bookmark-display-string bookmark))
1636                  (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1637              (elpher-insert-index-record display-string address)))
1638        (insert "No bookmarks found.\n")))
1639    (insert "\n-----------------------\n"
1640            "\n"
1641            "- u: return to previous page\n"
1642            "- x: delete selected bookmark\n"
1643            "- a: rename selected bookmark\n"
1644            "\n"
1645            "Bookmarks are stored in the file ")
1646    (let ((filename elpher-bookmarks-file)
1647          (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1648      (insert-text-button filename
1649                          'face 'link
1650                          'action (lambda (_)
1651                                    (interactive)
1652                                    (find-file filename))
1653                          'follow-link t
1654                          'help-echo help-string))
1655    (insert "\n")
1656    (elpher-restore-pos)))
1657
1658
1659 ;;; Bookmarks
1660 ;;
1661
1662 (defun elpher-make-bookmark (display-string url)
1663   "Make an elpher bookmark.
1664 DISPLAY-STRING determines how the bookmark will appear in the
1665 bookmark list, while URL is the url of the entry."
1666   (list display-string url))
1667
1668 (defun elpher-bookmark-display-string (bookmark)
1669   "Get the display string of BOOKMARK."
1670   (elt bookmark 0))
1671
1672 (defun elpher-set-bookmark-display-string (bookmark display-string)
1673   "Set the display string of BOOKMARK to DISPLAY-STRING."
1674   (setcar bookmark display-string))
1675
1676 (defun elpher-bookmark-url (bookmark)
1677   "Get the address for BOOKMARK."
1678   (elt bookmark 1))
1679
1680 (defun elpher-save-bookmarks (bookmarks)
1681   "Record the bookmark list BOOKMARKS to the user's bookmark file.
1682 Beware that this completely replaces the existing contents of the file."
1683   (let ((bookmark-dir (file-name-directory elpher-bookmarks-file)))
1684     (unless (file-directory-p bookmark-dir)
1685       (make-directory bookmark-dir)))
1686   (with-temp-file elpher-bookmarks-file
1687     (erase-buffer)
1688     (insert "; Elpher bookmarks file\n\n"
1689             "; Bookmarks are stored as a list of (label URL) items.\n"
1690             "; Feel free to edit by hand, but take care to ensure\n"
1691             "; the list structure remains intact.\n\n")
1692     (pp bookmarks (current-buffer))))
1693
1694 (defun elpher-load-bookmarks ()
1695   "Get the list of bookmarks from the users's bookmark file."
1696   (let ((bookmarks
1697          (with-temp-buffer
1698            (ignore-errors
1699              (insert-file-contents elpher-bookmarks-file)
1700              (goto-char (point-min))
1701              (read (current-buffer))))))
1702     (if (and bookmarks (listp (cadar bookmarks)))
1703         (progn
1704           (message "Reading old bookmark file. (Will be updated on write.)")
1705           (mapcar (lambda (old-bm)
1706                     (list (car old-bm)
1707                           (elpher-address-to-url (apply #'elpher-make-gopher-address
1708                                                         (cadr old-bm)))))
1709                   bookmarks))
1710       bookmarks)))
1711
1712 (defun elpher-add-address-bookmark (address display-string)
1713   "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1714 If ADDRESS is already bookmarked, update the label only."
1715   (let ((bookmarks (elpher-load-bookmarks))
1716         (url (elpher-address-to-url address)))
1717     (let ((existing-bookmark (rassoc (list url) bookmarks)))
1718       (if existing-bookmark
1719           (elpher-set-bookmark-display-string existing-bookmark display-string)
1720         (push (elpher-make-bookmark display-string url) bookmarks)))
1721     (elpher-save-bookmarks bookmarks)))
1722
1723 (defun elpher-remove-address-bookmark (address)
1724   "Remove any bookmark to ADDRESS."
1725   (let ((url (elpher-address-to-url address)))
1726     (elpher-save-bookmarks
1727      (seq-filter (lambda (bookmark)
1728                    (not (equal (elpher-bookmark-url bookmark) url)))
1729                  (elpher-load-bookmarks)))))
1730
1731 ;;; Integrations
1732 ;;
1733
1734 (defun elpher-org-link-store ()
1735   "Store link to an `elpher' page in org-mode."
1736   (when (eq major-mode 'elpher-mode)
1737     (let ((link (concat "elpher:" (elpher-info-current)))
1738           (desc (car elpher-current-page)))
1739       (org-link-store-props :type "elpher"
1740                             :link link
1741                             :description desc)
1742       t)))
1743
1744 (defun elpher-org-link-follow (link _args)
1745   "Follow an `elpher' link in an `org' buffer."
1746   (require 'elpher)
1747   (message (concat "Got link: " link))
1748   (when (or
1749          (string-match-p "^gemini://.+" link)
1750          (string-match-p "^gopher://.+" link)
1751          (string-match-p "^finger://.+" link))
1752     (elpher-go (string-remove-prefix "elpher:" link))))
1753
1754 (with-eval-after-load "org"
1755   ;; Use `org-link-set-parameters' if defined (org-mode 9+)
1756   (if (fboundp 'org-link-set-parameters)
1757       (org-link-set-parameters "elpher"
1758                                :store #'elpher-org-link-store
1759                                :follow #'elpher-org-link-follow)
1760     (org-add-link-type "mu4e" 'elpher-org-link-follow)
1761     (add-hook 'org-store-link-functions 'elpher-org-link-store)))
1762
1763 (defun browse-url-elpher (url &rest _args)
1764   "Browse URL. This function is used by `browse-url'."
1765   (interactive (browse-url-interactive-arg "Elpher URL: "))
1766   (elpher-go url))
1767
1768 (with-eval-after-load "browse-url"
1769   ;; Use elpher to open gopher, finger and gemini links
1770   (when (boundp 'browse-url-default-handlers)
1771     (add-to-list 'browse-url-default-handlers
1772                  '("^\\(gopher\\|finger\\|gemini\\)://" . browse-url-elpher)))
1773   ;; Register "gemini://" as a URI scheme so `browse-url' does the right thing
1774   (add-to-list 'thing-at-point-uri-schemes "gemini://"))
1775
1776 ;;; Interactive procedures
1777 ;;
1778
1779 (defun elpher-next-link ()
1780   "Move point to the next link on the current page."
1781   (interactive)
1782   (forward-button 1))
1783
1784 (defun elpher-prev-link ()
1785   "Move point to the previous link on the current page."
1786   (interactive)
1787   (backward-button 1))
1788
1789 (defun elpher-follow-current-link ()
1790   "Open the link or url at point."
1791   (interactive)
1792   (push-button))
1793
1794 ;;;###autoload
1795 (defun elpher-go (host-or-url)
1796   "Go to a particular gopher site HOST-OR-URL.
1797 When run interactively HOST-OR-URL is read from the minibuffer."
1798   (interactive "sGopher or Gemini URL: ")
1799   (let* ((cleaned-host-or-url (string-trim host-or-url))
1800          (address (elpher-address-from-url cleaned-host-or-url))
1801          (page (elpher-make-page cleaned-host-or-url address)))
1802     (switch-to-buffer elpher-buffer-name)
1803     (elpher-visit-page page)
1804     nil))
1805
1806 (defun elpher-go-current ()
1807   "Go to a particular site read from the minibuffer, initialized with the current URL."
1808   (interactive)
1809   (let ((address (elpher-page-address elpher-current-page)))
1810     (if (elpher-address-special-p address)
1811         (error "Command invalid for this page")
1812       (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1813         (elpher-visit-page (elpher-make-page url (elpher-address-from-url url)))))))
1814
1815 (defun elpher-redraw ()
1816   "Redraw current page."
1817   (interactive)
1818   (elpher-visit-page elpher-current-page))
1819
1820 (defun elpher-reload ()
1821   "Reload current page."
1822   (interactive)
1823   (elpher-reload-current-page))
1824
1825 (defun elpher-toggle-tls ()
1826   "Toggle TLS encryption mode for gopher."
1827   (interactive)
1828   (setq elpher-use-tls (not elpher-use-tls))
1829   (if elpher-use-tls
1830       (if (gnutls-available-p)
1831           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
1832         (setq elpher-use-tls nil)
1833         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1834     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
1835
1836 (defun elpher-view-raw ()
1837   "View raw server response for current page."
1838   (interactive)
1839   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1840       (error "This page was not generated by a server")
1841     (elpher-visit-page elpher-current-page
1842                        #'elpher-render-raw)))
1843
1844 (defun elpher-back ()
1845   "Go to previous site."
1846   (interactive)
1847   (elpher-visit-previous-page))
1848
1849 (defun elpher-back-to-start ()
1850   "Go all the way back to the start page."
1851   (interactive)
1852   (setq-local elpher-current-page nil)
1853   (setq-local elpher-history nil)
1854   (let ((start-page (elpher-make-page "Elpher Start Page"
1855                                       (elpher-make-special-address 'start))))
1856     (elpher-visit-page start-page)))
1857
1858 (defun elpher-download ()
1859   "Download the link at point."
1860   (interactive)
1861   (let ((button (button-at (point))))
1862     (if button
1863         (let ((page (button-get button 'elpher-page)))
1864           (if (elpher-address-special-p (elpher-page-address page))
1865               (error "Cannot download %s"
1866                      (elpher-page-display-string page))
1867             (elpher-visit-page (button-get button 'elpher-page)
1868                                #'elpher-render-download)))
1869       (error "No link selected"))))
1870
1871 (defun elpher-download-current ()
1872   "Download the current page."
1873   (interactive)
1874   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1875       (error "Cannot download %s"
1876              (elpher-page-display-string elpher-current-page))
1877     (elpher-visit-page (elpher-make-page
1878                         (elpher-page-display-string elpher-current-page)
1879                         (elpher-page-address elpher-current-page))
1880                        #'elpher-render-download
1881                        t)))
1882
1883 (defun elpher-build-link-map ()
1884   "Build alist mapping link names to destination pages in current buffer."
1885   (let ((link-map nil)
1886         (b (next-button (point-min) t)))
1887     (while b
1888       (push (cons (button-label b) b) link-map)
1889       (setq b (next-button (button-start b))))
1890     link-map))
1891
1892 (defun elpher-jump ()
1893   "Select a directory entry by name.  Similar to the info browser (m)enu command."
1894   (interactive)
1895   (let* ((link-map (elpher-build-link-map)))
1896     (if link-map
1897         (let ((key (let ((completion-ignore-case t))
1898                      (completing-read "Directory item/link: "
1899                                       link-map nil t))))
1900           (if (and key (> (length key) 0))
1901               (let ((b (cdr (assoc key link-map))))
1902                 (goto-char (button-start b))
1903                 (button-activate b)))))))
1904
1905 (defun elpher-root-dir ()
1906   "Visit root of current server."
1907   (interactive)
1908   (let ((address (elpher-page-address elpher-current-page)))
1909     (if (not (elpher-address-special-p address))
1910         (if (or (member (url-filename address) '("/" ""))
1911                 (and (elpher-address-gopher-p address)
1912                      (= (length (elpher-gopher-address-selector address)) 0)))
1913             (error "Already at root directory of current server")
1914           (let ((address-copy (elpher-address-from-url
1915                                (elpher-address-to-url address))))
1916             (setf (url-filename address-copy) "")
1917             (elpher-go (elpher-address-to-url address-copy))))
1918       (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
1919
1920 (defun elpher-bookmarks-current-p ()
1921   "Return non-nil if current page is a bookmarks page."
1922   (equal (elpher-address-type (elpher-page-address elpher-current-page))
1923          '(special bookmarks)))
1924
1925 (defun elpher-reload-bookmarks ()
1926   "Reload bookmarks if current page is a bookmarks page."
1927   (if (elpher-bookmarks-current-p)
1928       (elpher-reload-current-page)))
1929
1930 (defun elpher-bookmark-current ()
1931   "Bookmark the current page."
1932   (interactive)
1933   (let ((address (elpher-page-address elpher-current-page))
1934         (display-string (elpher-page-display-string elpher-current-page)))
1935     (if (not (elpher-address-special-p address))
1936         (let ((bookmark-display-string (read-string "Bookmark display string: "
1937                                                     display-string)))
1938           (elpher-add-address-bookmark address bookmark-display-string)
1939           (message "Bookmark added."))
1940       (error "Cannot bookmark %s" display-string))))
1941
1942 (defun elpher-bookmark-link ()
1943   "Bookmark the link at point."
1944   (interactive)
1945   (let ((button (button-at (point))))
1946     (if button
1947         (let* ((page (button-get button 'elpher-page))
1948                (address (elpher-page-address page))
1949                (display-string (elpher-page-display-string page)))
1950           (if (not (elpher-address-special-p address))
1951               (let ((bookmark-display-string (read-string "Bookmark display string: "
1952                                                           display-string)))
1953                 (elpher-add-address-bookmark address bookmark-display-string)
1954                 (elpher-reload-bookmarks)
1955                 (message "Bookmark added."))
1956             (error "Cannot bookmark %s" display-string)))
1957       (error "No link selected"))))
1958
1959 (defun elpher-unbookmark-current ()
1960   "Remove bookmark for the current page."
1961   (interactive)
1962   (let ((address (elpher-page-address elpher-current-page)))
1963     (when (and (not (elpher-address-special-p address))
1964                (y-or-n-p "Really remove bookmark for the current page? "))
1965       (elpher-remove-address-bookmark address)
1966       (message "Bookmark removed."))))
1967
1968 (defun elpher-unbookmark-link ()
1969   "Remove bookmark for the link at point."
1970   (interactive)
1971   (let ((button (button-at (point))))
1972     (if button
1973         (when (y-or-n-p "Really remove bookmark for this link? ")
1974           (let ((page (button-get button 'elpher-page)))
1975             (elpher-remove-address-bookmark (elpher-page-address page))
1976             (elpher-reload-bookmarks)
1977             (message "Bookmark removed.")))
1978       (error "No link selected"))))
1979
1980 ;;;###autoload
1981 (defun elpher-bookmarks ()
1982   "Visit bookmarks page."
1983   (interactive)
1984   (switch-to-buffer elpher-buffer-name)
1985   (elpher-visit-page
1986    (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
1987
1988 (defun elpher-info-page (page)
1989   "Display information on PAGE."
1990   (let ((display-string (elpher-page-display-string page))
1991         (address (elpher-page-address page)))
1992     (if (elpher-address-special-p address)
1993         (message "Special page: %s" display-string)
1994       (message "%s" (elpher-address-to-url address)))))
1995
1996 (defun elpher-info-link ()
1997   "Display information on page corresponding to link at point."
1998   (interactive)
1999   (let ((button (button-at (point))))
2000     (if button
2001         (elpher-info-page (button-get button 'elpher-page))
2002       (error "No item selected"))))
2003
2004 (defun elpher-info-current ()
2005   "Display information on current page."
2006   (interactive)
2007   (elpher-info-page elpher-current-page))
2008
2009 (defun elpher-copy-page-url (page)
2010   "Copy URL representation of address of PAGE to `kill-ring'."
2011   (let ((address (elpher-page-address page)))
2012     (if (elpher-address-special-p address)
2013         (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
2014       (let ((url (elpher-address-to-url address)))
2015         (message "Copied \"%s\" to kill-ring/clipboard." url)
2016         (kill-new url)))))
2017
2018 (defun elpher-copy-link-url ()
2019   "Copy URL of item at point to `kill-ring'."
2020   (interactive)
2021   (let ((button (button-at (point))))
2022     (if button
2023         (elpher-copy-page-url (button-get button 'elpher-page))
2024       (error "No item selected"))))
2025
2026 (defun elpher-copy-current-url ()
2027   "Copy URL of current page to `kill-ring'."
2028   (interactive)
2029   (elpher-copy-page-url elpher-current-page))
2030
2031 (defun elpher-set-gopher-coding-system ()
2032   "Specify an explicit character coding system for gopher selectors."
2033   (interactive)
2034   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
2035     (setq elpher-user-coding-system system)
2036     (if system
2037         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
2038       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
2039
2040
2041 ;;; Mode and keymap
2042 ;;
2043
2044 (defvar elpher-mode-map
2045   (let ((map (make-sparse-keymap)))
2046     (define-key map (kbd "TAB") 'elpher-next-link)
2047     (define-key map (kbd "<backtab>") 'elpher-prev-link)
2048     (define-key map (kbd "C-M-i") 'elpher-prev-link)
2049     (define-key map (kbd "u") 'elpher-back)
2050     (define-key map (kbd "U") 'elpher-back-to-start)
2051     (define-key map [mouse-3] 'elpher-back)
2052     (define-key map (kbd "O") 'elpher-root-dir)
2053     (define-key map (kbd "g") 'elpher-go)
2054     (define-key map (kbd "o") 'elpher-go-current)
2055     (define-key map (kbd "r") 'elpher-redraw)
2056     (define-key map (kbd "R") 'elpher-reload)
2057     (define-key map (kbd "T") 'elpher-toggle-tls)
2058     (define-key map (kbd ".") 'elpher-view-raw)
2059     (define-key map (kbd "d") 'elpher-download)
2060     (define-key map (kbd "D") 'elpher-download-current)
2061     (define-key map (kbd "m") 'elpher-jump)
2062     (define-key map (kbd "i") 'elpher-info-link)
2063     (define-key map (kbd "I") 'elpher-info-current)
2064     (define-key map (kbd "c") 'elpher-copy-link-url)
2065     (define-key map (kbd "C") 'elpher-copy-current-url)
2066     (define-key map (kbd "a") 'elpher-bookmark-link)
2067     (define-key map (kbd "A") 'elpher-bookmark-current)
2068     (define-key map (kbd "x") 'elpher-unbookmark-link)
2069     (define-key map (kbd "X") 'elpher-unbookmark-current)
2070     (define-key map (kbd "B") 'elpher-bookmarks)
2071     (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
2072     (define-key map (kbd "F") 'elpher-forget-current-certificate)
2073     (when (fboundp 'evil-define-key*)
2074       (evil-define-key* 'motion map
2075         (kbd "TAB") 'elpher-next-link
2076         (kbd "C-") 'elpher-follow-current-link
2077         (kbd "C-t") 'elpher-back
2078         (kbd "u") 'elpher-back
2079         (kbd "U") 'elpher-back-to-start
2080         [mouse-3] 'elpher-back
2081         (kbd "g") 'elpher-go
2082         (kbd "o") 'elpher-go-current
2083         (kbd "r") 'elpher-redraw
2084         (kbd "R") 'elpher-reload
2085         (kbd "T") 'elpher-toggle-tls
2086         (kbd ".") 'elpher-view-raw
2087         (kbd "d") 'elpher-download
2088         (kbd "D") 'elpher-download-current
2089         (kbd "m") 'elpher-jump
2090         (kbd "i") 'elpher-info-link
2091         (kbd "I") 'elpher-info-current
2092         (kbd "c") 'elpher-copy-link-url
2093         (kbd "C") 'elpher-copy-current-url
2094         (kbd "a") 'elpher-bookmark-link
2095         (kbd "A") 'elpher-bookmark-current
2096         (kbd "x") 'elpher-unbookmark-link
2097         (kbd "X") 'elpher-unbookmark-current
2098         (kbd "B") 'elpher-bookmarks
2099         (kbd "S") 'elpher-set-gopher-coding-system
2100         (kbd "F") 'elpher-forget-current-certificate))
2101     map)
2102   "Keymap for gopher client.")
2103
2104 (define-derived-mode elpher-mode special-mode "elpher"
2105   "Major mode for elpher, an elisp gopher client.
2106
2107 This mode is automatically enabled by the interactive
2108 functions which initialize the gopher client, namely
2109 `elpher', `elpher-go' and `elpher-bookmarks'."
2110   (setq-local elpher-current-page nil)
2111   (setq-local elpher-history nil)
2112   (setq-local elpher-buffer-name (buffer-name)))
2113
2114 (when (fboundp 'evil-set-initial-state)
2115   (evil-set-initial-state 'elpher-mode 'motion))
2116
2117
2118 ;;; Main start procedure
2119 ;;
2120
2121 ;;;###autoload
2122 (defun elpher (&optional arg)
2123   "Start elpher with default landing page.
2124 The buffer used for Elpher sessions is determined by the value of
2125 ‘elpher-buffer-name’.  If there is already an Elpher session active in
2126 that buffer, Emacs will simply switch to it.  Otherwise, a new session
2127 will begin.  A numeric prefix arg (as in ‘C-u 42 M-x elpher RET’)
2128 switches to the session with that number, creating it if necessary.  A
2129 nonnumeric prefix arg means to create a new session.  Returns the
2130 buffer selected (or created)."
2131   (interactive "P")
2132   (let* ((name (default-value 'elpher-buffer-name))
2133          (buf (cond ((numberp arg)
2134                      (get-buffer-create (format "%s<%d>" name arg)))
2135                     (arg
2136                      (generate-new-buffer name))
2137                     (t
2138                      (get-buffer-create name)))))
2139     (pop-to-buffer-same-window buf)
2140     (unless (buffer-modified-p)
2141       (elpher-mode)
2142       (let ((start-page (elpher-make-page "Elpher Start Page"
2143                                           (elpher-make-special-address 'start))))
2144         (elpher-visit-page start-page))
2145       "Started Elpher."))); Otherwise (elpher) evaluates to start page string.
2146
2147 ;;; elpher.el ends here