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