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