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