Switch URL and Name position in the menu
[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.0
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.0"
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-regexp-grouping-backslash))
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) "/"))
284                 (setf (url-filename url) "/1")))
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 (defvar elpher-content-cache (make-hash-table :test 'equal))
407 (defvar elpher-pos-cache (make-hash-table :test 'equal))
408
409 (defun elpher-get-cached-content (address)
410   "Retrieve the cached content for ADDRESS, or nil if none exists."
411   (gethash address elpher-content-cache))
412
413 (defun elpher-cache-content (address content)
414   "Set the content cache for ADDRESS to CONTENT."
415   (puthash address content elpher-content-cache))
416
417 (defun elpher-get-cached-pos (address)
418   "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
419   (gethash address elpher-pos-cache))
420
421 (defun elpher-cache-pos (address pos)
422   "Set the cursor position cache for ADDRESS to POS."
423   (puthash address pos elpher-pos-cache))
424
425
426 ;; Page
427
428 (defun elpher-make-page (display-string address)
429   "Create a page with DISPLAY-STRING and ADDRESS."
430   (list display-string address))
431
432 (defun elpher-page-display-string (page)
433   "Retrieve the display string corresponding to PAGE."
434   (elt page 0))
435
436 (defun elpher-page-address (page)
437   "Retrieve the address corresponding to PAGE."
438   (elt page 1))
439
440 (defun elpher-page-set-address (page new-address)
441   "Set the address corresponding to PAGE to NEW-ADDRESS."
442   (setcar (cdr page) new-address))
443
444 (defvar elpher-current-page nil)        ; buffer local
445 (defvar elpher-history nil)             ; buffer local
446
447 (defun elpher-visit-page (page &optional renderer no-history)
448   "Visit PAGE using its own renderer or RENDERER, if non-nil.
449 Additionally, push PAGE onto the stack of previously-visited pages,
450 unless NO-HISTORY is non-nil."
451   (elpher-save-pos)
452   (elpher-process-cleanup)
453   (unless (or no-history
454               (equal (elpher-page-address elpher-current-page)
455                      (elpher-page-address page)))
456     (push elpher-current-page elpher-history))
457   (setq-local elpher-current-page page)
458   (let* ((address (elpher-page-address page))
459          (type (elpher-address-type address))
460          (type-record (cdr (assoc type elpher-type-map))))
461     (if type-record
462         (funcall (car type-record)
463                  (if renderer
464                      renderer
465                    (cadr type-record)))
466       (elpher-visit-previous-page)
467       (pcase type
468         (`(gopher ,type-char)
469          (error "Unsupported gopher selector type '%c' for '%s'"
470                 type-char (elpher-address-to-url address)))
471         (other
472          (error "Unsupported address type '%S' for '%s'"
473                 other (elpher-address-to-url address)))))))
474
475 (defun elpher-visit-previous-page ()
476   "Visit the previous page in the history."
477   (let ((previous-page (pop elpher-history)))
478     (if previous-page
479         (elpher-visit-page previous-page nil t)
480       (error "No previous page"))))
481       
482 (defun elpher-reload-current-page ()
483   "Reload the current page, discarding any existing cached content."
484   (elpher-cache-content (elpher-page-address elpher-current-page) nil)
485   (elpher-visit-page elpher-current-page))
486
487 (defun elpher-save-pos ()
488   "Save the current position of point to the current page."
489   (when elpher-current-page
490     (elpher-cache-pos (elpher-page-address elpher-current-page) (point))))
491
492 (defun elpher-restore-pos ()
493   "Restore the position of point to that cached in the current page."
494   (let ((pos (elpher-get-cached-pos (elpher-page-address elpher-current-page))))
495     (if pos
496         (goto-char pos)
497       (goto-char (point-min)))))
498
499
500 ;;; Buffer preparation
501 ;;
502
503 (defvar elpher-buffer-name "*elpher*"
504   "The default name of the Elpher buffer.")
505
506 (defun elpher-update-header ()
507   "If `elpher-use-header' is true, display current page info in window header."
508   (if elpher-use-header
509       (let* ((display-string (elpher-page-display-string elpher-current-page))
510              (address (elpher-page-address elpher-current-page))
511              (tls-string (if (and (not (elpher-address-special-p address))
512                                   (member (elpher-address-protocol address)
513                                           '("gophers" "gemini")))
514                              " [TLS encryption]"
515                            ""))
516              (header (concat display-string
517                              (propertize tls-string 'face 'bold))))
518         (setq header-line-format header))))
519
520 (defmacro elpher-with-clean-buffer (&rest args)
521   "Evaluate ARGS with a clean *elpher* buffer as current."
522   `(with-current-buffer elpher-buffer-name
523      (unless (eq major-mode 'elpher-mode)
524        ;; avoid resetting buffer-local variables
525        (elpher-mode))
526      (let ((inhibit-read-only t))
527        (setq-local network-security-level
528                    (default-value 'network-security-level))
529        (erase-buffer)
530        (elpher-update-header)
531        ,@args)))
532
533 (defun elpher-buffer-message (string &optional line)
534   "Replace first line in elpher buffer with STRING.
535 If LINE is non-nil, replace that line instead."
536   (with-current-buffer elpher-buffer-name
537     (let ((inhibit-read-only t))
538       (goto-char (point-min))
539       (if line
540           (forward-line line))
541       (let ((data (match-data)))
542         (unwind-protect
543             (progn
544               (re-search-forward "^.*$")
545               (replace-match string))
546           (set-match-data data))))))
547
548
549 ;;; Text Processing
550 ;;
551
552 (defvar elpher-user-coding-system nil
553   "User-specified coding system to use for decoding text responses.")
554
555 (defun elpher-decode (string)
556   "Decode STRING using autodetected or user-specified coding system."
557   (decode-coding-string string
558                         (if elpher-user-coding-system
559                             elpher-user-coding-system
560                           (detect-coding-string string t))))
561
562 (defun elpher-preprocess-text-response (string)
563   "Preprocess text selector response contained in STRING.
564 This involes decoding the character representation, and clearing
565 away CRs and any terminating period."
566   (elpher-decode (replace-regexp-in-string "\n\.\n$" "\n"
567                                            (replace-regexp-in-string "\r" "" string))))
568
569
570 ;;; Network error reporting
571 ;;
572
573 (defun elpher-network-error (address error)
574   "Display ERROR message following unsuccessful negotiation with ADDRESS.
575 ERROR can be either an error object or a string."
576   (elpher-with-clean-buffer
577    (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
578            "When attempting to retrieve " (elpher-address-to-url address) ":\n"
579            (if (stringp error) error (error-message-string error)) "\n"
580            (propertize "\n----------------\n\n" 'face 'error)
581            "Press 'u' to return to the previous page.")))
582
583
584 ;;; General network communication
585 ;;
586
587 (defvar elpher-network-timer nil
588   "Timer used for network connections.")
589
590 (defvar elpher-use-tls nil
591   "If non-nil, use TLS to communicate with gopher servers.")
592
593 (defvar elpher-client-certificate nil
594   "If non-nil, contains client certificate details to use for TLS connections.")
595
596 (defun elpher-process-cleanup ()
597   "Immediately shut down any extant elpher process and timers."
598   (let ((p (get-process "elpher-process")))
599     (if p (delete-process p)))
600   (if (timerp elpher-network-timer)
601       (cancel-timer elpher-network-timer)))
602
603 (defun elpher-get-host-response (address default-port query-string response-processor
604                                          &optional use-tls force-ipv4)
605   "Generic function for retrieving data from ADDRESS.
606
607 When ADDRESS lacks a specific port, DEFAULT-PORT is used instead.
608 QUERY-STRING is a string sent to the host specified by ADDRESS to
609 illicet a response.  This response is passed as an argument to the
610 function RESPONSE-PROCESSOR.
611
612 If non-nil, USE-TLS specifies that the connection is to be made over
613 TLS.  If set to gemini, the certificate verification will be disabled
614 unless `elpher-gemini-TLS-cert-checks' is non-nil.
615
616 If non-nil, FORCE-IPV4 causes the network connection to be made over
617 ipv4 only.  (The default behaviour when this is not set depends on
618 the host operating system and the local network capabilities."
619   (if (and use-tls (not (gnutls-available-p)))
620       (error "Use of TLS requires Emacs to be compiled with GNU TLS support")
621     (unless (< (elpher-address-port address) 65536)
622       (error "Cannot establish network connection: port number > 65536"))
623     (when (and (eq use-tls 'gemini) (not elpher-gemini-TLS-cert-checks))
624       (setq-local network-security-level 'low))
625     (condition-case nil
626         (let* ((kill-buffer-query-functions nil)
627                (port (elpher-address-port address))
628                (host (elpher-address-host address))
629                (response-string-parts nil)
630                (bytes-received 0)
631                (hkbytes-received 0)
632                (proc (make-network-process :name "elpher-process"
633                                            :host host
634                                            :family (and force-ipv4 'ipv4)
635                                            :service (if (> port 0) port default-port)
636                                            :buffer nil
637                                            :coding 'binary
638                                            :noquery t
639                                            :nowait t
640                                            :tls-parameters
641                                            (and use-tls
642                                                 (cons 'gnutls-x509pki
643                                                       (gnutls-boot-parameters
644                                                        :type 'gnutls-x509pki
645                                                        :hostname host
646                                                        :keylist
647                                                        (elpher-get-current-keylist address))))))
648                (timer (run-at-time elpher-connection-timeout nil
649                                    (lambda ()
650                                      (elpher-process-cleanup)
651                                      (cond
652                                         ; Try again with IPv4
653                                       ((not force-ipv4)
654                                        (message "Connection timed out.  Retrying with IPv4.")
655                                        (elpher-get-host-response address default-port
656                                                                  query-string
657                                                                  response-processor
658                                                                  use-tls t))
659                                       ((and use-tls
660                                             (not (eq use-tls 'gemini))
661                                             (or elpher-auto-disengage-TLS
662                                                 (y-or-n-p
663                                                  "TLS connetion failed.  Disable TLS mode and retry? ")))
664                                        (setq elpher-use-tls nil)
665                                        (elpher-get-host-response address default-port
666                                                                  query-string
667                                                                  response-processor
668                                                                  nil force-ipv4))
669                                       (t
670                                        (elpher-network-error address "Connection time-out.")))))))
671           (setq elpher-network-timer timer)
672           (elpher-buffer-message (concat "Connecting to " host "..."
673                                          " (press 'u' to abort)"))
674           (set-process-filter proc
675                               (lambda (_proc string)
676                                 (when timer
677                                   (cancel-timer timer)
678                                   (setq timer nil))
679                                 (setq bytes-received (+ bytes-received (length string)))
680                                 (let ((new-hkbytes-received (/ bytes-received 102400)))
681                                   (when (> new-hkbytes-received hkbytes-received)
682                                     (setq hkbytes-received new-hkbytes-received)
683                                     (elpher-buffer-message
684                                         (concat "("
685                                                 (number-to-string (/ hkbytes-received 10.0))
686                                                 " MB read)")
687                                         1)))
688                                 (setq response-string-parts
689                                       (cons string response-string-parts))))
690           (set-process-sentinel proc
691                                 (lambda (proc event)
692                                   (when timer
693                                     (cancel-timer timer))
694                                   (condition-case the-error
695                                       (cond
696                                        ((string-prefix-p "open" event)    ; request URL
697                                         (elpher-buffer-message
698                                          (concat "Connected to " host ". Receiving data..."
699                                                  " (press 'u' to abort)"))
700                                         (let ((inhibit-eol-conversion t))
701                                           (process-send-string proc query-string)))
702                                        ((string-prefix-p "deleted" event)) ; do nothing
703                                        ((and (not response-string-parts)
704                                              (not (or elpher-ipv4-always force-ipv4)))
705                                         ; Try again with IPv4
706                                         (message "Connection failed. Retrying with IPv4.")
707                                         (elpher-get-host-response address default-port
708                                                                   query-string
709                                                                   response-processor
710                                                                   use-tls t))
711                                        (response-string-parts
712                                         (elpher-with-clean-buffer
713                                          (insert "Data received.  Rendering..."))
714                                         (funcall response-processor
715                                                  (apply #'concat (reverse response-string-parts)))
716                                         (elpher-restore-pos))
717                                        (t
718                                         (error "No response from server")))
719                                     (error
720                                      (elpher-network-error address the-error))))))
721       (error
722        (error "Error initiating connection to server")))))
723
724
725 ;;; Client-side TLS Certificate Management
726 ;;
727
728 (defun elpher-generate-certificate (common-name key-file cert-file &optional temporary)
729   "Generate a key and a self-signed client TLS certificate using openssl.
730
731 The Common Name field of the certificate is set to COMMON-NAME.  The
732 arguments KEY-FILE and CERT-FILE should contain the absolute paths of
733 the key and certificate files to write.
734
735 If TEMPORARY is non-nil, the certificate will be given an exporation
736 period of one day, and the key and certificate files will be deleted
737 when the certificate is no longer needed for the current session.
738
739 Otherwise, the certificate will be given a 100 year expiration period
740 and the files will not be deleted.
741
742 The function returns a list containing the current host name, the
743 temporary flag, and the key and cert file names in the form required
744 by `gnutls-boot-parameters`."
745   (let ((exp-key-file (expand-file-name key-file))
746         (exp-cert-file (expand-file-name cert-file)))
747     (condition-case nil
748         (progn
749           (call-process elpher-openssl-command nil nil nil
750                         "req" "-x509" "-newkey" "rsa:2048"
751                         "-days" (if temporary "1" "36500")
752                         "-nodes"
753                         "-subj" (concat "/CN=" common-name)
754                         "-keyout" exp-key-file
755                         "-out" exp-cert-file)
756           (list (elpher-address-host (elpher-page-address elpher-current-page))
757                 temporary exp-key-file exp-cert-file))
758       (error
759        (message "Check that openssl is installed, or customize `elpher-openssl-command`.")
760        (error "Program 'openssl', required for certificate generation, not found")))))
761
762 (defun elpher-generate-throwaway-certificate ()
763   "Generate and return details of a throwaway certificate.
764 The key and certificate files will be deleted when they are no
765 longer needed for this session."
766   (let* ((file-base (make-temp-name "elpher"))
767          (key-file (concat temporary-file-directory file-base ".key"))
768          (cert-file (concat temporary-file-directory file-base ".crt")))
769     (elpher-generate-certificate file-base key-file cert-file t)))
770
771 (defun elpher-generate-persistent-certificate (file-base common-name)
772   "Generate and return details of a persistent certificate.
773 The argument FILE-BASE is used as the base for the key and certificate
774 files, while COMMON-NAME specifies the common name field of the
775 certificate.
776
777 The key and certificate files are written to in `elpher-certificate-directory'."
778   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
779          (cert-file (concat elpher-certificate-directory file-base ".crt")))
780     (elpher-generate-certificate common-name key-file cert-file)))
781
782 (defun elpher-get-existing-certificate (file-base)
783   "Return a certificate object corresponding to an existing certificate.
784 It is assumed that the key files FILE-BASE.key and FILE-BASE.crt exist in
785 the directory `elpher-certificate-directory'."
786   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
787          (cert-file (concat elpher-certificate-directory file-base ".crt")))
788     (list (elpher-address-host (elpher-page-address elpher-current-page))
789           nil
790           (expand-file-name key-file)
791           (expand-file-name cert-file))))
792
793 (defun elpher-install-and-use-existing-certificate (key-file-src cert-file-src file-base)
794   "Install a key+certificate file pair in `elpher-certificate-directory'.
795 The strings KEY-FILE-SRC and CERT-FILE-SRC are the existing key and
796 certificate files to install.  The argument FILE-BASE is used as the
797 base for the installed key and certificate files."
798   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
799          (cert-file (concat elpher-certificate-directory file-base ".crt")))
800     (if (or (file-exists-p key-file)
801             (file-exists-p cert-file))
802         (error "A certificate with base name %s is already installed" file-base))
803     (copy-file key-file-src key-file)
804     (copy-file cert-file-src cert-file)
805     (list (elpher-address-host (elpher-page-address elpher-current-page))
806           nil
807           (expand-file-name key-file)
808           (expand-file-name cert-file))))
809
810 (defun elpher-list-existing-certificates ()
811   "Return a list of the persistent certificates in `elpher-certificate-directory'."
812   (mapcar
813    (lambda (file)
814      (file-name-sans-extension file))
815    (directory-files elpher-certificate-directory nil "\.key$")))
816
817 (defun elpher-forget-current-certificate ()
818   "Causes any current certificate to be forgotten.)
819 In the case of throwaway certificates, the key and certificate files
820 are also deleted."
821   (interactive)
822   (when elpher-client-certificate
823     (unless (and (called-interactively-p 'any)
824                  (not (y-or-n-p (concat "Really forget client certificate? "
825                                         "(Throwaway certificates will be deleted.)"))))
826       (when (cadr elpher-client-certificate)
827         (delete-file (elt elpher-client-certificate 2))
828         (delete-file (elt elpher-client-certificate 3)))
829       (setq elpher-client-certificate nil)
830       (if (called-interactively-p 'any)
831           (message "Client certificate forgotten.")))))
832
833 (defun elpher-get-current-keylist (address)
834   "Retrieve the `gnutls-boot-parameters'-compatable keylist.
835
836 This is obtained from the client certificate described by
837 `elpher-current-certificate', if one is available and the host for
838 that certificate matches the host in ADDRESS.
839
840 If `elpher-current-certificate' is non-nil, and its host name doesn't
841 match that of ADDRESS, the certificate is forgotten."
842   (if elpher-client-certificate
843       (if (string= (car elpher-client-certificate)
844                    (elpher-address-host address))
845           (list (cddr elpher-client-certificate))
846         (elpher-forget-current-certificate)
847         (message "Disabling client certificate for new host")
848         nil)
849     nil))
850
851
852 ;;; Gopher selector retrieval
853 ;;
854
855 (defun elpher-get-gopher-response (address renderer)
856   "Get response string from gopher server at ADDRESS and render using RENDERER."
857   (elpher-get-host-response address 70
858                             (concat (elpher-gopher-address-selector address) "\r\n")
859                             renderer
860                             (or (string= (elpher-address-protocol address) "gophers")
861                                 elpher-use-tls)))
862
863 (defun elpher-get-gopher-page (renderer)
864   "Getter function for gopher pages.
865 The RENDERER procedure is used to display the contents of the page
866 once they are retrieved from the gopher server."
867   (let* ((address (elpher-page-address elpher-current-page))
868          (content (elpher-get-cached-content address)))
869     (if (and content (funcall renderer nil))
870         (elpher-with-clean-buffer
871          (insert content)
872          (elpher-restore-pos))
873       (elpher-with-clean-buffer
874        (insert "LOADING... (use 'u' to cancel)\n"))
875       (condition-case the-error
876           (elpher-get-gopher-response address renderer)
877         (error
878          (elpher-network-error address the-error))))))
879
880 ;; Index rendering
881
882 (defun elpher-insert-index (string)
883   "Insert the index corresponding to STRING into the current buffer."
884   ;; Should be able to split directly on CRLF, but some non-conformant
885   ;; LF-only servers sadly exist, hence the following.
886   (let ((str-processed (elpher-preprocess-text-response string)))
887     (dolist (line (split-string str-processed "\n"))
888       (ignore-errors
889         (unless (= (length line) 0)
890           (let* ((type (elt line 0))
891                  (fields (split-string (substring line 1) "\t"))
892                  (display-string (elt fields 0))
893                  (selector (elt fields 1))
894                  (host (elt fields 2))
895                  (port (if (elt fields 3)
896                            (string-to-number (elt fields 3))
897                          nil))
898                  (address (elpher-make-gopher-address type selector host port)))
899             (elpher-insert-index-record display-string address)))))))
900
901 (defun elpher-insert-margin (&optional type-name)
902   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
903   (if type-name
904       (progn
905         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
906                         (concat
907                          (propertize "[" 'face 'elpher-margin-brackets)
908                          (propertize type-name 'face 'elpher-margin-key)
909                          (propertize "]" 'face 'elpher-margin-brackets))))
910         (insert " "))
911     (insert (make-string elpher-margin-width ?\s))))
912
913 (defun elpher--page-button-help (_window buffer pos)
914   "Function called by Emacs to generate mouse-over text.
915 The arguments specify the BUFFER and the POS within the buffer of the item
916 for which help is required.  The function returns the help to be
917 displayed.  The _WINDOW argument is currently unused."
918   (with-current-buffer buffer
919     (let ((button (button-at pos)))
920       (when button
921         (let* ((page (button-get button 'elpher-page))
922                (address (elpher-page-address page)))
923           (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
924                                                 address
925                                               (elpher-address-to-url address))))))))
926
927 (defun elpher-insert-index-record (display-string &optional address)
928   "Function to insert an index record into the current buffer.
929 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
930 If ADDRESS is not supplied or nil the record is rendered as an
931 'information' line."
932   (let* ((type (if address (elpher-address-type address) nil))
933          (type-map-entry (cdr (assoc type elpher-type-map))))
934     (if type-map-entry
935         (let* ((margin-code (elt type-map-entry 2))
936                (face (elt type-map-entry 3))
937                (filtered-display-string (ansi-color-filter-apply display-string))
938                (page (elpher-make-page filtered-display-string address)))
939           (elpher-insert-margin margin-code)
940           (insert-text-button filtered-display-string
941                               'face face
942                               'elpher-page page
943                               'action #'elpher-click-link
944                               'follow-link t
945                               'help-echo #'elpher--page-button-help))
946       (pcase type
947         ('nil ;; Information
948          (elpher-insert-margin)
949          (let ((propertized-display-string
950                 (propertize display-string 'face 'elpher-info)))
951            (insert (elpher-process-text-for-display propertized-display-string))))
952         (`(gopher ,selector-type) ;; Unknown
953          (elpher-insert-margin (concat (char-to-string selector-type) "?"))
954          (insert (propertize display-string
955                              'face 'elpher-unknown)))))
956     (insert "\n")))
957
958 (defun elpher-click-link (button)
959   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
960   (let ((page (button-get button 'elpher-page)))
961     (elpher-visit-page page)))
962
963 (defun elpher-render-index (data &optional _mime-type-string)
964   "Render DATA as an index.  MIME-TYPE-STRING is unused."
965   (elpher-with-clean-buffer
966    (if (not data)
967        t
968      (elpher-insert-index data)
969      (elpher-cache-content (elpher-page-address elpher-current-page)
970                            (buffer-string)))))
971
972 ;; Text rendering
973
974 (defconst elpher-url-regex
975   "\\([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\-_~?/@|#]\\)?\\)?"
976   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
977
978 (defun elpher-buttonify-urls (string)
979   "Turn substrings which look like urls in STRING into clickable buttons."
980   (with-temp-buffer
981     (insert string)
982     (goto-char (point-min))
983     (while (re-search-forward elpher-url-regex nil t)
984       (let ((page (elpher-make-page (substring-no-properties (match-string 0))
985                                     (elpher-address-from-url (match-string 0)))))
986           (make-text-button (match-beginning 0)
987                             (match-end 0)
988                             'elpher-page  page
989                             'action #'elpher-click-link
990                             'follow-link t
991                             'help-echo #'elpher--page-button-help
992                             'face 'button)))
993     (buffer-string)))
994
995 (defconst elpher-ansi-regex "\x1b\\[[^m]*m"
996   "Wildly incomplete regexp used to strip out some troublesome ANSI escape sequences.")
997
998 (defun elpher-process-text-for-display (string)
999   "Perform any desired processing of STRING prior to display as text.
1000 Currently includes buttonifying URLs and processing ANSI escape codes."
1001   (elpher-buttonify-urls (if elpher-filter-ansi-from-text
1002                              (ansi-color-filter-apply string)
1003                            (ansi-color-apply string))))
1004
1005 (defun elpher-render-text (data &optional _mime-type-string)
1006   "Render DATA as text.  MIME-TYPE-STRING is unused."
1007   (elpher-with-clean-buffer
1008    (if (not data)
1009        t
1010      (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
1011      (elpher-cache-content
1012       (elpher-page-address elpher-current-page)
1013       (buffer-string)))))
1014
1015 ;; Image retrieval
1016
1017 (defun elpher-render-image (data &optional _mime-type-string)
1018   "Display DATA as image.  MIME-TYPE-STRING is unused."
1019   (if (not data)
1020       nil
1021     (if (display-images-p)
1022         (progn
1023           (let ((image (create-image
1024                         data
1025                         nil t)))
1026             (elpher-with-clean-buffer
1027              (insert-image image)
1028              (elpher-restore-pos))))
1029       (elpher-render-download data))))
1030
1031 ;; Search retrieval and rendering
1032
1033 (defun elpher-get-gopher-query-page (renderer)
1034   "Getter for gopher addresses requiring input.
1035 The response is rendered using the rendering function RENDERER."
1036    (let* ((address (elpher-page-address elpher-current-page))
1037           (content (elpher-get-cached-content address))
1038           (aborted t))
1039     (if (and content (funcall renderer nil))
1040         (elpher-with-clean-buffer
1041          (insert content)
1042          (elpher-restore-pos)
1043          (message "Displaying cached search results.  Reload to perform a new search."))
1044       (unwind-protect
1045           (let* ((query-string (read-string "Query: "))
1046                  (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
1047                  (search-address (elpher-make-gopher-address ?1
1048                                                              query-selector
1049                                                              (elpher-address-host address)
1050                                                              (elpher-address-port address)
1051                                                              (equal (elpher-address-type address) "gophers"))))
1052             (setq aborted nil)
1053
1054             (elpher-with-clean-buffer
1055              (insert "LOADING RESULTS... (use 'u' to cancel)"))
1056             (elpher-get-gopher-response search-address renderer))
1057         (if aborted
1058             (elpher-visit-previous-page))))))
1059  
1060 ;; Raw server response rendering
1061
1062 (defun elpher-render-raw (data &optional mime-type-string)
1063   "Display raw DATA in buffer.  MIME-TYPE-STRING is also displayed if provided."
1064   (if (not data)
1065       nil
1066     (elpher-with-clean-buffer
1067      (when mime-type-string
1068        (insert "MIME type specified by server: '" mime-type-string "'\n"))
1069      (insert data)
1070      (goto-char (point-min)))
1071     (message "Displaying raw server response.  Reload or redraw to return to standard view.")))
1072
1073 ;; File save "rendering"
1074
1075 (defun elpher-render-download (data &optional _mime-type-string)
1076   "Save DATA to file.  MIME-TYPE-STRING is unused."
1077   (if (not data)
1078       nil
1079     (let* ((address (elpher-page-address elpher-current-page))
1080            (selector (if (elpher-address-gopher-p address)
1081                          (elpher-gopher-address-selector address)
1082                        (elpher-address-filename address))))
1083       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1084       (let* ((filename-proposal (file-name-nondirectory selector))
1085              (filename (read-file-name "Download complete. Save file as: "
1086                                        nil nil nil
1087                                        (if (> (length filename-proposal) 0)
1088                                            filename-proposal
1089                                          "download.file"))))
1090         (let ((coding-system-for-write 'binary))
1091           (with-temp-file filename
1092             (insert data)))
1093         (message (format "Saved to file %s." filename))))))
1094
1095 ;; HTML rendering
1096
1097 (defun elpher-render-html (data &optional _mime-type-string)
1098   "Render DATA as HTML using shr.  MIME-TYPE-STRING is unused."
1099   (elpher-with-clean-buffer
1100    (if (not data)
1101        t
1102      (let ((dom (with-temp-buffer
1103                   (insert data)
1104                   (libxml-parse-html-region (point-min) (point-max)))))
1105        (shr-insert-document dom)))))
1106
1107 ;; Gemini page retrieval
1108
1109 (defvar elpher-gemini-redirect-chain)
1110
1111 (defun elpher-get-gemini-response (address renderer)
1112   "Get response string from gemini server at ADDRESS and render using RENDERER."
1113   (elpher-get-host-response address 1965
1114                             (concat (elpher-address-to-url address) "\r\n")
1115                             (lambda (response-string)
1116                               (elpher-process-gemini-response response-string renderer))
1117                             'gemini))
1118
1119 (defun elpher-parse-gemini-response (response)
1120   "Parse the RESPONSE string and return a list of components.
1121 The list is of the form (code meta body).  A response of nil implies
1122 that the response was malformed."
1123   (let ((header-end-idx (string-match "\r\n" response)))
1124     (if header-end-idx
1125         (let ((header (string-trim (substring response 0 header-end-idx)))
1126               (body (substring response (+ header-end-idx 2))))
1127           (if (>= (length header) 2)
1128               (let ((code (substring header 0 2))
1129                     (meta (string-trim (substring header 2))))
1130                 (list code meta body))
1131             (error "Malformed response: No response status found in header %s" header)))
1132       (error "Malformed response: No CRLF-delimited header found in response %s" response))))
1133
1134 (defun elpher-process-gemini-response (response-string renderer)
1135   "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
1136   (let ((response-components (elpher-parse-gemini-response response-string)))
1137     (let ((response-code (elt response-components 0))
1138           (response-meta (elt response-components 1))
1139           (response-body (elt response-components 2)))
1140       (pcase (elt response-code 0)
1141         (?1 ; Input required
1142          (elpher-with-clean-buffer
1143           (insert "Gemini server is requesting input."))
1144          (let* ((query-string
1145                  (if (eq (elt response-code 1) ?1)
1146                      (read-passwd (concat response-meta ": "))
1147                    (read-string (concat response-meta ": "))))
1148                 (query-address (seq-copy (elpher-page-address elpher-current-page)))
1149                 (old-fname (url-filename query-address)))
1150            (setf (url-filename query-address)
1151                  (concat old-fname "?" (url-build-query-string `((,query-string)))))
1152            (elpher-get-gemini-response query-address renderer)))
1153         (?2 ; Normal response
1154          (funcall renderer response-body response-meta))
1155         (?3 ; Redirect
1156          (message "Following redirect to %s" response-meta)
1157          (if (>= (length elpher-gemini-redirect-chain) 5)
1158              (error "More than 5 consecutive redirects followed"))
1159          (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
1160            (if (member redirect-address elpher-gemini-redirect-chain)
1161                (error "Redirect loop detected"))
1162            (if (not (string= (elpher-address-protocol redirect-address)
1163                              "gemini"))
1164                (error "Server tried to automatically redirect to non-gemini URL: %s"
1165                       response-meta))
1166            (elpher-page-set-address elpher-current-page redirect-address)
1167            (add-to-list 'elpher-gemini-redirect-chain redirect-address)
1168            (elpher-get-gemini-response redirect-address renderer)))
1169         (?4 ; Temporary failure
1170          (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
1171                 response-code response-meta))
1172         (?5 ; Permanent failure
1173          (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
1174                 response-code response-meta))
1175         (?6 ; Client certificate required
1176          (elpher-with-clean-buffer
1177           (if elpher-client-certificate
1178               (insert "Gemini server does not recognise the provided TLS certificate:\n\n")
1179             (insert "Gemini server is requesting a valid TLS certificate:\n\n"))
1180           (auto-fill-mode 1)
1181           (elpher-gemini-insert-text response-meta))
1182          (let ((chosen-certificate (elpher-choose-client-certificate)))
1183            (unless chosen-certificate
1184              (error "Gemini server requires a client certificate and none was provided"))
1185            (setq elpher-client-certificate chosen-certificate))
1186          (elpher-with-clean-buffer)
1187          (elpher-get-gemini-response (elpher-page-address elpher-current-page) renderer))
1188         (_other
1189          (error "Gemini server response unknown: %s %s"
1190                 response-code response-meta))))))
1191
1192 (defun elpher-choose-client-certificate ()
1193   "Prompt for a client certificate to use to establish a TLS connection."
1194   (let* ((read-answer-short t))
1195     (pcase (read-answer "What do you want to do? "
1196                         '(("throwaway" ?t
1197                            "generate and use throw-away certificate")
1198                           ("persistent" ?p
1199                            "generate new or use existing persistent certificate")
1200                           ("abort" ?a
1201                            "stop immediately")))
1202       ("throwaway"
1203        (setq elpher-client-certificate (elpher-generate-throwaway-certificate)))
1204       ("persistent"
1205        (let* ((existing-certificates (elpher-list-existing-certificates))
1206               (file-base (completing-read
1207                           "Nickname for new or existing certificate (autocompletes, empty response aborts): "
1208                           existing-certificates)))
1209          (if (string-empty-p (string-trim file-base))
1210              nil
1211            (if (member file-base existing-certificates)
1212                (setq elpher-client-certificate
1213                      (elpher-get-existing-certificate file-base))
1214              (pcase (read-answer "Generate new certificate or install externally-generated one? "
1215                                  '(("new" ?n
1216                                     "generate new certificate")
1217                                    ("install" ?i
1218                                     "install existing certificate")
1219                                    ("abort" ?a
1220                                     "stop immediately")))
1221                ("new"
1222                 (let ((common-name (read-string "Common Name field for new certificate: "
1223                                                 file-base)))
1224                   (message "New key and self-signed certificate written to %s"
1225                            elpher-certificate-directory)
1226                   (elpher-generate-persistent-certificate file-base common-name)))
1227                ("install"
1228                 (let* ((cert-file (read-file-name "Certificate file: " nil nil t))
1229                        (key-file (read-file-name "Key file: " nil nil t)))
1230                   (message "Key and certificate installed in %s for future use"
1231                            elpher-certificate-directory)
1232                   (elpher-install-and-use-existing-certificate key-file
1233                                                                cert-file
1234                                                                file-base)))
1235                ("abort" nil))))))
1236       ("abort" nil))))
1237
1238 (defun elpher-get-gemini-page (renderer)
1239   "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1240   (let* ((address (elpher-page-address elpher-current-page))
1241          (content (elpher-get-cached-content address)))
1242     (condition-case the-error
1243         (if (and content (funcall renderer nil))
1244             (elpher-with-clean-buffer
1245               (insert content)
1246               (elpher-restore-pos))
1247           (elpher-with-clean-buffer
1248            (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1249           (setq elpher-gemini-redirect-chain nil)
1250           (elpher-get-gemini-response address renderer))
1251       (error
1252        (elpher-network-error address the-error)))))
1253
1254 (defun elpher-render-gemini (body &optional mime-type-string)
1255   "Render gemini response BODY with rendering MIME-TYPE-STRING."
1256   (if (not body)
1257       t
1258     (let* ((mime-type-string* (if (or (not mime-type-string)
1259                                       (string-empty-p mime-type-string))
1260                                   "text/gemini; charset=utf-8"
1261                                 mime-type-string))
1262            (mime-type-split (split-string mime-type-string* ";" t))
1263            (mime-type (string-trim (car mime-type-split)))
1264            (parameters (mapcar (lambda (s)
1265                                  (let ((key-val (split-string s "=")))
1266                                    (list (downcase (string-trim (car key-val)))
1267                                          (downcase (string-trim (cadr key-val))))))
1268                                (cdr mime-type-split))))
1269       (when (string-prefix-p "text/" mime-type)
1270         (setq body (decode-coding-string
1271                     body
1272                     (if (assoc "charset" parameters)
1273                         (intern (cadr (assoc "charset" parameters)))
1274                       'utf-8)))
1275         (setq body (replace-regexp-in-string "\r" "" body)))
1276       (pcase mime-type
1277         ((or "text/gemini" "")
1278          (elpher-render-gemini-map body parameters))
1279         ("text/html"
1280          (elpher-render-html body))
1281         ((pred (string-prefix-p "text/"))
1282          (elpher-render-gemini-plain-text body parameters))
1283         ((pred (string-prefix-p "image/"))
1284          (elpher-render-image body))
1285         (_other
1286          (elpher-render-download body))))))
1287
1288 (defun elpher-gemini-get-link-url (link-line)
1289   "Extract the url portion of LINK-LINE, a gemini map file link line.
1290 Returns nil in the event that the contents of the line following the
1291 => prefix are empty."
1292   (let ((l (split-string (substring link-line 2))))
1293     (if l
1294         (string-trim (elt l 0))
1295       nil)))
1296
1297 (defun elpher-gemini-get-link-display-string (link-line)
1298   "Extract the display string portion of LINK-LINE, a gemini map file link line.
1299 Returns the url portion in the event that the display-string portion is empty."
1300   (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1301          (idx (string-match "[ \t]" rest)))
1302     (string-trim (if idx
1303                      (substring rest (+ idx 1))
1304                    rest))))
1305
1306 (defun elpher-collapse-dot-sequences (filename)
1307   "Collapse dot sequences in FILENAME.
1308 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1309   (let* ((path (split-string filename "/"))
1310          (path-reversed-normalized
1311           (seq-reduce (lambda (a b)
1312                         (cond ((and a (equal b "..") (cdr a)))
1313                               ((and (not a) (equal b "..")) a) ;leading .. are dropped
1314                               ((equal b ".") a)
1315                               (t (cons b a))))
1316                       path nil)))
1317     (string-join (reverse path-reversed-normalized) "/")))
1318
1319 (defun elpher-address-from-gemini-url (url)
1320   "Extract address from URL with defaults as per gemini map files.
1321 While there's obviously some redundancy here between this function and
1322 `elpher-address-from-url', gemini map file URLs require enough special
1323 treatment that a separate function is warranted."
1324   (let ((address (url-generic-parse-url url))
1325         (current-address (elpher-page-address elpher-current-page)))
1326     (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1327       (setf (url-fullness address) t)
1328       (if (url-host address) ;if there is an explicit host, filenames are absolute
1329           (if (string-empty-p (url-filename address))
1330               (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1331         (setf (url-host address) (url-host current-address))
1332         (setf (url-port address) (url-port current-address))
1333         (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1334           (setf (url-filename address)
1335                 (concat (file-name-directory (url-filename current-address))
1336                         (url-filename address)))))
1337       (unless (url-type address)
1338         (setf (url-type address) "gemini"))
1339       (when (equal (url-type address) "gemini")
1340         (setf (url-filename address)
1341               (elpher-collapse-dot-sequences (url-filename address)))))
1342     (elpher-remove-redundant-ports address)))
1343
1344 (defun elpher-gemini-insert-link (link-line)
1345   "Insert link described by LINK-LINE into a text/gemini document."
1346   (let* ((url (elpher-gemini-get-link-url link-line))
1347          (display-string (elpher-gemini-get-link-display-string link-line))
1348          (address (elpher-address-from-gemini-url url))
1349          (type (if address (elpher-address-type address) nil))
1350          (type-map-entry (cdr (assoc type elpher-type-map))))
1351     (when display-string
1352       (insert elpher-gemini-link-string)
1353       (if type-map-entry
1354           (let* ((face (elt type-map-entry 3))
1355                  (filtered-display-string (ansi-color-filter-apply display-string))
1356                  (page (elpher-make-page filtered-display-string address)))
1357             (insert-text-button filtered-display-string
1358                                 'face face
1359                                 'elpher-page page
1360                                 'action #'elpher-click-link
1361                                 'follow-link t
1362                                 'help-echo #'elpher--page-button-help))
1363         (insert (propertize display-string 'face 'elpher-unknown)))
1364       (insert "\n"))))
1365   
1366 (defun elpher-gemini-insert-header (header-line)
1367   "Insert header described by HEADER-LINE into a text/gemini document.
1368 The gemini map file line describing the header is given
1369 by HEADER-LINE."
1370   (when (string-match "^\\(#+\\)[ \t]*" header-line)
1371     (let* ((level (length (match-string 1 header-line)))
1372            (header (substring header-line (match-end 0)))
1373            (face (pcase level
1374                    (1 'elpher-gemini-heading1)
1375                    (2 'elpher-gemini-heading2)
1376                    (3 'elpher-gemini-heading3)
1377                    (_ 'default)))
1378            (fill-column (/ (* fill-column
1379                               (font-get (font-spec :name (face-font 'default)) :size))
1380                            (font-get (font-spec :name (face-font face)) :size))))
1381       (unless (display-graphic-p)
1382         (insert (make-string level ?#) " "))
1383       (insert (propertize header 'face face))
1384       (newline))))
1385
1386 (defun elpher-gemini-insert-text (text-line)
1387   "Insert a plain non-preformatted TEXT-LINE into a text/gemini document.
1388 This function uses Emacs' auto-fill to wrap text sensibly to a maximum
1389 width defined by elpher-gemini-max-fill-width."
1390   (string-match "\\(^[ \t]*\\)\\(\*[ \t]+\\|>[ \t]*\\)?" text-line)
1391   (let* ((processed-text-line (if (match-string 2 text-line)
1392                                   (concat
1393                                    (replace-regexp-in-string "\*"
1394                                                              elpher-gemini-bullet-string
1395                                                              (match-string 0 text-line))
1396                                    (substring text-line (match-end 0)))
1397                                 text-line))
1398          (adaptive-fill-mode nil)
1399          (fill-prefix (if (match-string 2 text-line)
1400                           (replace-regexp-in-string "[>\*]" " " (match-string 0 text-line))
1401                         nil)))
1402     (insert (elpher-process-text-for-display processed-text-line))
1403     (newline)))
1404
1405 (defun elpher-render-gemini-map (data _parameters)
1406   "Render DATA as a gemini map file, PARAMETERS is currently unused."
1407   (elpher-with-clean-buffer
1408    (let ((preformatted nil))
1409      (auto-fill-mode 1)
1410      (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1411      (dolist (line (split-string data "\n"))
1412        (cond
1413         ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1414         (preformatted (insert (elpher-process-text-for-display
1415                                (propertize line 'face 'elpher-gemini-preformatted))
1416                               "\n"))
1417         ((string-prefix-p "=>" line) (elpher-gemini-insert-link line))
1418         ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1419         (t (elpher-gemini-insert-text line)))))
1420    (elpher-cache-content
1421     (elpher-page-address elpher-current-page)
1422     (buffer-string))))
1423
1424 (defun elpher-render-gemini-plain-text (data _parameters)
1425   "Render DATA as plain text file.  PARAMETERS is currently unused."
1426   (elpher-with-clean-buffer
1427    (insert (elpher-process-text-for-display data))
1428    (elpher-cache-content
1429     (elpher-page-address elpher-current-page)
1430     (buffer-string))))
1431
1432
1433 ;; Finger page connection
1434
1435 (defun elpher-get-finger-page (renderer)
1436   "Opens a finger connection to the current page address.
1437 The result is rendered using RENDERER."
1438   (let* ((address (elpher-page-address elpher-current-page))
1439          (content (elpher-get-cached-content address)))
1440     (if (and content (funcall renderer nil))
1441         (elpher-with-clean-buffer
1442          (insert content)
1443          (elpher-restore-pos))
1444       (elpher-with-clean-buffer
1445        (insert "LOADING... (use 'u' to cancel)\n"))
1446       (condition-case the-error
1447           (let* ((kill-buffer-query-functions nil)
1448                  (user (let ((filename (elpher-address-filename address)))
1449                          (if (> (length filename) 1)
1450                              (substring filename 1)
1451                            (elpher-address-user address)))))
1452             (elpher-get-host-response address 79
1453                                       (concat user "\r\n")
1454                                       renderer))
1455         (error
1456          (elpher-network-error address the-error))))))
1457
1458
1459 ;; Telnet page connection
1460
1461 (defun elpher-get-telnet-page (renderer)
1462   "Opens a telnet connection to the current page address (RENDERER must be nil)."
1463   (when renderer
1464     (elpher-visit-previous-page)
1465     (error "Command not supported for telnet URLs"))
1466   (let* ((address (elpher-page-address elpher-current-page))
1467          (host (elpher-address-host address))
1468          (port (elpher-address-port address)))
1469     (elpher-visit-previous-page)
1470     (if (> port 0)
1471         (telnet host port)
1472       (telnet host))))
1473
1474
1475 ;; Other URL page opening
1476
1477 (defun elpher-get-other-url-page (renderer)
1478   "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1479   (when renderer
1480     (elpher-visit-previous-page)
1481     (error "Command not supported for general URLs"))
1482   (let* ((address (elpher-page-address elpher-current-page))
1483          (url (elpher-address-to-url address)))
1484     (progn
1485       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1486       (message "Opening URL...")
1487       (if elpher-open-urls-with-eww
1488           (browse-web url)
1489         (browse-url url)))))
1490
1491
1492 ;; Start page page retrieval
1493
1494 (defun elpher-get-start-page (renderer)
1495   "Getter which displays the start page (RENDERER must be nil)."
1496   (when renderer
1497     (elpher-visit-previous-page)
1498     (error "Command not supported for start page"))
1499   (elpher-with-clean-buffer
1500    (insert "     --------------------------------------------\n"
1501            "           Elpher Gopher and Gemini Client       \n"
1502            "                   version " elpher-version "\n"
1503            "     --------------------------------------------\n"
1504            "\n"
1505            "Default bindings:\n"
1506            "\n"
1507            " - TAB/Shift-TAB: next/prev item on current page\n"
1508            " - RET/mouse-1: open item under cursor\n"
1509            " - m: select an item on current page by name (autocompletes)\n"
1510            " - u/mouse-3/U: return to previous page or to the start page\n"
1511            " - o/O: visit different selector or the root menu of the current server\n"
1512            " - g: go to a particular address (gopher, gemini, finger)\n"
1513            " - d/D: download item under cursor or current page\n"
1514            " - i/I: info on item under cursor or current page\n"
1515            " - c/C: copy URL representation of item under cursor or current page\n"
1516            " - a/A: bookmark the item under cursor or current page\n"
1517            " - x/X: remove bookmark for item under cursor or current page\n"
1518            " - B: visit the bookmarks page\n"
1519            " - r: redraw current page (using cached contents if available)\n"
1520            " - R: reload current page (regenerates cache)\n"
1521            " - S: set character coding system for gopher (default is to autodetect)\n"
1522            " - T: toggle TLS gopher mode\n"
1523            " - F: forget/discard current TLS client certificate\n"
1524            " - .: display the raw server response for the current page\n"
1525            "\n"
1526            "Start your exploration of gopher space and gemini:\n")
1527    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1528                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1529    (elpher-insert-index-record "Project Gemini home page"
1530                                (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1531    (insert "\n"
1532            "Alternatively, select a search engine and enter some search terms:\n")
1533    (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1534                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1535    (elpher-insert-index-record "Gemini Search Engine (GUS)"
1536                                (elpher-address-from-url "gemini://gus.guru/search"))
1537    (insert "\n"
1538            "This page contains your bookmarked sites (also visit with B):\n")
1539    (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1540    (insert "\n"
1541            "For Elpher release news or to leave feedback, visit:\n")
1542    (elpher-insert-index-record "The Elpher Project Page"
1543                                (elpher-make-gopher-address ?1
1544                                                            "/projects/elpher/"
1545                                                            "thelambdalab.xyz"
1546                                                            70))
1547    (insert "\n"
1548            "** Refer to the ")
1549    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1550      (insert-text-button "Elpher info manual"
1551                          'face 'link
1552                          'action (lambda (_)
1553                                    (interactive)
1554                                    (info "(elpher)"))
1555                          'follow-link t
1556                          'help-echo help-string))
1557    (insert " for the full documentation. **\n")
1558    (insert (propertize
1559             (concat "  (This should be available if you have installed Elpher using\n"
1560                     "   MELPA. Otherwise you will have to install the manual yourself.)\n")
1561             'face 'shadow))
1562    (elpher-restore-pos)))
1563
1564 ;; Bookmarks page page retrieval
1565
1566 (defun elpher-get-bookmarks-page (renderer)
1567   "Getter to load and display the current bookmark list (RENDERER must be nil)."
1568   (when renderer
1569     (elpher-visit-previous-page)
1570     (error "Command not supported for bookmarks page"))
1571   (elpher-with-clean-buffer
1572    (insert "---- Bookmark list ----\n\n")
1573    (let ((bookmarks (elpher-load-bookmarks)))
1574      (if bookmarks
1575          (dolist (bookmark bookmarks)
1576            (let ((display-string (elpher-bookmark-display-string bookmark))
1577                  (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1578              (elpher-insert-index-record display-string address)))
1579        (insert "No bookmarks found.\n")))
1580    (insert "\n-----------------------\n"
1581            "\n"
1582            "- u: return to previous page\n"
1583            "- x: delete selected bookmark\n"
1584            "- a: rename selected bookmark\n"
1585            "\n"
1586            "Bookmarks are stored in the file ")
1587    (let ((filename elpher-bookmarks-file)
1588          (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1589      (insert-text-button filename
1590                          'face 'link
1591                          'action (lambda (_)
1592                                    (interactive)
1593                                    (find-file filename))
1594                          'follow-link t
1595                          'help-echo help-string))
1596    (insert "\n")
1597    (elpher-restore-pos)))
1598   
1599
1600 ;;; Bookmarks
1601 ;;
1602
1603 (defun elpher-make-bookmark (display-string url)
1604   "Make an elpher bookmark.
1605 DISPLAY-STRING determines how the bookmark will appear in the
1606 bookmark list, while URL is the url of the entry."
1607   (list display-string url))
1608   
1609 (defun elpher-bookmark-display-string (bookmark)
1610   "Get the display string of BOOKMARK."
1611   (elt bookmark 0))
1612
1613 (defun elpher-set-bookmark-display-string (bookmark display-string)
1614   "Set the display string of BOOKMARK to DISPLAY-STRING."
1615   (setcar bookmark display-string))
1616
1617 (defun elpher-bookmark-url (bookmark)
1618   "Get the address for BOOKMARK."
1619   (elt bookmark 1))
1620
1621 (defun elpher-save-bookmarks (bookmarks)
1622   "Record the bookmark list BOOKMARKS to the user's bookmark file.
1623 Beware that this completely replaces the existing contents of the file."
1624   (with-temp-file elpher-bookmarks-file
1625     (erase-buffer)
1626     (insert "; Elpher bookmarks file\n\n"
1627             "; Bookmarks are stored as a list of (label URL) items.\n"
1628             "; Feel free to edit by hand, but take care to ensure\n"
1629             "; the list structure remains intact.\n\n")
1630     (pp bookmarks (current-buffer))))
1631
1632 (defun elpher-load-bookmarks ()
1633   "Get the list of bookmarks from the users's bookmark file."
1634   (let ((bookmarks
1635          (with-temp-buffer
1636            (ignore-errors
1637              (insert-file-contents elpher-bookmarks-file)
1638              (goto-char (point-min))
1639              (read (current-buffer))))))
1640     (if (and bookmarks (listp (cadar bookmarks)))
1641         (progn
1642           (message "Reading old bookmark file. (Will be updated on write.)")
1643           (mapcar (lambda (old-bm)
1644                     (list (car old-bm)
1645                           (elpher-address-to-url (apply #'elpher-make-gopher-address
1646                                                         (cadr old-bm)))))
1647                   bookmarks))
1648       bookmarks)))
1649
1650 (defun elpher-add-address-bookmark (address display-string)
1651   "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1652 If ADDRESS is already bookmarked, update the label only."
1653   (let ((bookmarks (elpher-load-bookmarks))
1654         (url (elpher-address-to-url address)))
1655     (let ((existing-bookmark (rassoc (list url) bookmarks)))
1656       (if existing-bookmark
1657           (elpher-set-bookmark-display-string existing-bookmark display-string)
1658         (push (elpher-make-bookmark display-string url) bookmarks)))
1659     (elpher-save-bookmarks bookmarks)))
1660
1661 (defun elpher-remove-address-bookmark (address)
1662   "Remove any bookmark to ADDRESS."
1663   (let ((url (elpher-address-to-url address)))
1664     (elpher-save-bookmarks
1665      (seq-filter (lambda (bookmark)
1666                    (not (equal (elpher-bookmark-url bookmark) url)))
1667                  (elpher-load-bookmarks)))))
1668
1669 ;;; Interactive procedures
1670 ;;
1671
1672 (defun elpher-next-link ()
1673   "Move point to the next link on the current page."
1674   (interactive)
1675   (forward-button 1))
1676
1677 (defun elpher-prev-link ()
1678   "Move point to the previous link on the current page."
1679   (interactive)
1680   (backward-button 1))
1681
1682 (defun elpher-follow-current-link ()
1683   "Open the link or url at point."
1684   (interactive)
1685   (push-button))
1686
1687 (defun elpher-go (host-or-url)
1688   "Go to a particular gopher site HOST-OR-URL.
1689 When run interactively HOST-OR-URL is read from the minibuffer."
1690   (interactive "sGopher or Gemini URL: ")
1691   (let* ((cleaned-host-or-url (string-trim host-or-url))
1692          (address (elpher-address-from-url cleaned-host-or-url))
1693          (page (elpher-make-page cleaned-host-or-url address)))
1694     (switch-to-buffer elpher-buffer-name)
1695     (elpher-visit-page page)
1696     nil))
1697
1698 (defun elpher-go-current ()
1699   "Go to a particular site read from the minibuffer, initialized with the current URL."
1700   (interactive)
1701   (let ((address (elpher-page-address elpher-current-page)))
1702     (if (elpher-address-special-p address)
1703         (error "Command invalid for this page")
1704       (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1705         (elpher-visit-page (elpher-make-page url (elpher-address-from-url url)))))))
1706
1707 (defun elpher-redraw ()
1708   "Redraw current page."
1709   (interactive)
1710   (elpher-visit-page elpher-current-page))
1711
1712 (defun elpher-reload ()
1713   "Reload current page."
1714   (interactive)
1715   (elpher-reload-current-page))
1716
1717 (defun elpher-toggle-tls ()
1718   "Toggle TLS encryption mode for gopher."
1719   (interactive)
1720   (setq elpher-use-tls (not elpher-use-tls))
1721   (if elpher-use-tls
1722       (if (gnutls-available-p)
1723           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
1724         (setq elpher-use-tls nil)
1725         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1726     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
1727
1728 (defun elpher-view-raw ()
1729   "View raw server response for current page."
1730   (interactive)
1731   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1732       (error "This page was not generated by a server")
1733     (elpher-visit-page elpher-current-page
1734                        #'elpher-render-raw)))
1735
1736 (defun elpher-back ()
1737   "Go to previous site."
1738   (interactive)
1739   (elpher-visit-previous-page))
1740
1741 (defun elpher-back-to-start ()
1742   "Go all the way back to the start page."
1743   (interactive)
1744   (setq-local elpher-current-page nil)
1745   (setq-local elpher-history nil)
1746   (let ((start-page (elpher-make-page "Elpher Start Page"
1747                                       (elpher-make-special-address 'start))))
1748     (elpher-visit-page start-page)))
1749
1750 (defun elpher-download ()
1751   "Download the link at point."
1752   (interactive)
1753   (let ((button (button-at (point))))
1754     (if button
1755         (let ((page (button-get button 'elpher-page)))
1756           (if (elpher-address-special-p (elpher-page-address page))
1757               (error "Cannot download %s"
1758                      (elpher-page-display-string page))
1759             (elpher-visit-page (button-get button 'elpher-page)
1760                                #'elpher-render-download)))
1761       (error "No link selected"))))
1762
1763 (defun elpher-download-current ()
1764   "Download the current page."
1765   (interactive)
1766   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1767       (error "Cannot download %s"
1768              (elpher-page-display-string elpher-current-page))
1769     (elpher-visit-page (elpher-make-page
1770                         (elpher-page-display-string elpher-current-page)
1771                         (elpher-page-address elpher-current-page))
1772                        #'elpher-render-download
1773                        t)))
1774
1775 (defun elpher-build-link-map ()
1776   "Build alist mapping link names to destination pages in current buffer."
1777   (let ((link-map nil)
1778         (b (next-button (point-min) t)))
1779     (while b
1780       (push (cons (button-label b) b) link-map)
1781       (setq b (next-button (button-start b))))
1782     link-map))
1783
1784 (defun elpher-jump ()
1785   "Select a directory entry by name.  Similar to the info browser (m)enu command."
1786   (interactive)
1787   (let* ((link-map (elpher-build-link-map)))
1788     (if link-map
1789         (let ((key (let ((completion-ignore-case t))
1790                      (completing-read "Directory item/link: "
1791                                       link-map nil t))))
1792           (if (and key (> (length key) 0))
1793               (let ((b (cdr (assoc key link-map))))
1794                 (goto-char (button-start b))
1795                 (button-activate b)))))))
1796
1797 (defun elpher-root-dir ()
1798   "Visit root of current server."
1799   (interactive)
1800   (let ((address (elpher-page-address elpher-current-page)))
1801     (if (not (elpher-address-special-p address))
1802         (if (or (member (url-filename address) '("/" ""))
1803                 (and (elpher-address-gopher-p address)
1804                      (= (length (elpher-gopher-address-selector address)) 0)))
1805             (error "Already at root directory of current server")
1806           (let ((address-copy (elpher-address-from-url
1807                                (elpher-address-to-url address))))
1808             (setf (url-filename address-copy) "")
1809             (elpher-go (elpher-address-to-url address-copy))))
1810       (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
1811
1812 (defun elpher-bookmarks-current-p ()
1813   "Return non-nil if current page is a bookmarks page."
1814   (equal (elpher-address-type (elpher-page-address elpher-current-page))
1815          '(special bookmarks)))
1816
1817 (defun elpher-reload-bookmarks ()
1818   "Reload bookmarks if current page is a bookmarks page."
1819   (if (elpher-bookmarks-current-p)
1820       (elpher-reload-current-page)))
1821
1822 (defun elpher-bookmark-current ()
1823   "Bookmark the current page."
1824   (interactive)
1825   (let ((address (elpher-page-address elpher-current-page))
1826         (display-string (elpher-page-display-string elpher-current-page)))
1827     (if (not (elpher-address-special-p address))
1828         (let ((bookmark-display-string (read-string "Bookmark display string: "
1829                                                     display-string)))
1830           (elpher-add-address-bookmark address bookmark-display-string)
1831           (message "Bookmark added."))
1832       (error "Cannot bookmark %s" display-string))))
1833
1834 (defun elpher-bookmark-link ()
1835   "Bookmark the link at point."
1836   (interactive)
1837   (let ((button (button-at (point))))
1838     (if button
1839         (let* ((page (button-get button 'elpher-page))
1840                (address (elpher-page-address page))
1841                (display-string (elpher-page-display-string page)))
1842           (if (not (elpher-address-special-p address))
1843               (let ((bookmark-display-string (read-string "Bookmark display string: "
1844                                                           display-string)))
1845                 (elpher-add-address-bookmark address bookmark-display-string)
1846                 (elpher-reload-bookmarks)
1847                 (message "Bookmark added."))
1848             (error "Cannot bookmark %s" display-string)))
1849       (error "No link selected"))))
1850
1851 (defun elpher-unbookmark-current ()
1852   "Remove bookmark for the current page."
1853   (interactive)
1854   (let ((address (elpher-page-address elpher-current-page)))
1855     (when (and (not (elpher-address-special-p address))
1856                (y-or-n-p "Really remove bookmark for the current page? "))
1857       (elpher-remove-address-bookmark address)
1858       (message "Bookmark removed."))))
1859
1860 (defun elpher-unbookmark-link ()
1861   "Remove bookmark for the link at point."
1862   (interactive)
1863   (let ((button (button-at (point))))
1864     (if button
1865         (when (y-or-n-p "Really remove bookmark for this link? ")
1866           (let ((page (button-get button 'elpher-page)))
1867             (elpher-remove-address-bookmark (elpher-page-address page))
1868             (elpher-reload-bookmarks)
1869             (message "Bookmark removed.")))
1870       (error "No link selected"))))
1871
1872 (defun elpher-bookmarks ()
1873   "Visit bookmarks page."
1874   (interactive)
1875   (switch-to-buffer elpher-buffer-name)
1876   (elpher-visit-page
1877    (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
1878
1879 (defun elpher-info-page (page)
1880   "Display information on PAGE."
1881   (let ((display-string (elpher-page-display-string page))
1882         (address (elpher-page-address page)))
1883     (if (elpher-address-special-p address)
1884         (message "Special page: %s" display-string)
1885       (message "%s" (elpher-address-to-url address)))))
1886
1887 (defun elpher-info-link ()
1888   "Display information on page corresponding to link at point."
1889   (interactive)
1890   (let ((button (button-at (point))))
1891     (if button
1892         (elpher-info-page (button-get button 'elpher-page))
1893       (error "No item selected"))))
1894   
1895 (defun elpher-info-current ()
1896   "Display information on current page."
1897   (interactive)
1898   (elpher-info-page elpher-current-page))
1899
1900 (defun elpher-copy-page-url (page)
1901   "Copy URL representation of address of PAGE to `kill-ring'."
1902   (let ((address (elpher-page-address page)))
1903     (if (elpher-address-special-p address)
1904         (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
1905       (let ((url (elpher-address-to-url address)))
1906         (message "Copied \"%s\" to kill-ring/clipboard." url)
1907         (kill-new url)))))
1908
1909 (defun elpher-copy-link-url ()
1910   "Copy URL of item at point to `kill-ring'."
1911   (interactive)
1912   (let ((button (button-at (point))))
1913     (if button
1914         (elpher-copy-page-url (button-get button 'elpher-page))
1915       (error "No item selected"))))
1916
1917 (defun elpher-copy-current-url ()
1918   "Copy URL of current page to `kill-ring'."
1919   (interactive)
1920   (elpher-copy-page-url elpher-current-page))
1921
1922 (defun elpher-set-gopher-coding-system ()
1923   "Specify an explicit character coding system for gopher selectors."
1924   (interactive)
1925   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
1926     (setq elpher-user-coding-system system)
1927     (if system
1928         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
1929       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
1930
1931
1932 ;;; Mode and keymap
1933 ;;
1934
1935 (defvar elpher-mode-map
1936   (let ((map (make-sparse-keymap)))
1937     (define-key map (kbd "TAB") 'elpher-next-link)
1938     (define-key map (kbd "<backtab>") 'elpher-prev-link)
1939     (define-key map (kbd "C-M-i") 'elpher-prev-link)
1940     (define-key map (kbd "u") 'elpher-back)
1941     (define-key map (kbd "U") 'elpher-back-to-start)
1942     (define-key map [mouse-3] 'elpher-back)
1943     (define-key map (kbd "O") 'elpher-root-dir)
1944     (define-key map (kbd "g") 'elpher-go)
1945     (define-key map (kbd "o") 'elpher-go-current)
1946     (define-key map (kbd "r") 'elpher-redraw)
1947     (define-key map (kbd "R") 'elpher-reload)
1948     (define-key map (kbd "T") 'elpher-toggle-tls)
1949     (define-key map (kbd ".") 'elpher-view-raw)
1950     (define-key map (kbd "d") 'elpher-download)
1951     (define-key map (kbd "D") 'elpher-download-current)
1952     (define-key map (kbd "m") 'elpher-jump)
1953     (define-key map (kbd "i") 'elpher-info-link)
1954     (define-key map (kbd "I") 'elpher-info-current)
1955     (define-key map (kbd "c") 'elpher-copy-link-url)
1956     (define-key map (kbd "C") 'elpher-copy-current-url)
1957     (define-key map (kbd "a") 'elpher-bookmark-link)
1958     (define-key map (kbd "A") 'elpher-bookmark-current)
1959     (define-key map (kbd "x") 'elpher-unbookmark-link)
1960     (define-key map (kbd "X") 'elpher-unbookmark-current)
1961     (define-key map (kbd "B") 'elpher-bookmarks)
1962     (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
1963     (define-key map (kbd "F") 'elpher-forget-current-certificate)
1964     (when (fboundp 'evil-define-key*)
1965       (evil-define-key* 'motion map
1966         (kbd "TAB") 'elpher-next-link
1967         (kbd "C-") 'elpher-follow-current-link
1968         (kbd "C-t") 'elpher-back
1969         (kbd "u") 'elpher-back
1970         (kbd "U") 'elpher-back-to-start
1971         [mouse-3] 'elpher-back
1972         (kbd "g") 'elpher-go
1973         (kbd "o") 'elpher-go-current
1974         (kbd "r") 'elpher-redraw
1975         (kbd "R") 'elpher-reload
1976         (kbd "T") 'elpher-toggle-tls
1977         (kbd ".") 'elpher-view-raw
1978         (kbd "d") 'elpher-download
1979         (kbd "D") 'elpher-download-current
1980         (kbd "m") 'elpher-jump
1981         (kbd "i") 'elpher-info-link
1982         (kbd "I") 'elpher-info-current
1983         (kbd "c") 'elpher-copy-link-url
1984         (kbd "C") 'elpher-copy-current-url
1985         (kbd "a") 'elpher-bookmark-link
1986         (kbd "A") 'elpher-bookmark-current
1987         (kbd "x") 'elpher-unbookmark-link
1988         (kbd "X") 'elpher-unbookmark-current
1989         (kbd "B") 'elpher-bookmarks
1990         (kbd "S") 'elpher-set-gopher-coding-system
1991         (kbd "F") 'elpher-forget-current-certificate))
1992     map)
1993   "Keymap for gopher client.")
1994
1995 (define-derived-mode elpher-mode special-mode "elpher"
1996   "Major mode for elpher, an elisp gopher client.
1997
1998 This mode is automatically enabled by the interactive
1999 functions which initialize the gopher client, namely
2000 `elpher', `elpher-go' and `elpher-bookmarks'."
2001   (setq-local elpher-current-page nil)
2002   (setq-local elpher-history nil)
2003   (setq-local elpher-buffer-name (buffer-name)))
2004
2005 (when (fboundp 'evil-set-initial-state)
2006   (evil-set-initial-state 'elpher-mode 'motion))
2007
2008 ;;; Menu
2009 ;;
2010
2011 (defun elpher-menu (&optional arg)
2012   "Show a list of all your `elpher' buffers.
2013 With an optional argument, add all the history items, too."
2014   (interactive "P")
2015   (switch-to-buffer (get-buffer-create "*Elpher Menu*"))
2016   (elpher-menu-mode)
2017   (elpher-menu-refresh arg)
2018   (tabulated-list-print))
2019
2020 (defvar elpher-menu-mode-map
2021   (let ((map (make-sparse-keymap))
2022         (menu-map (make-sparse-keymap)))
2023     (set-keymap-parent map tabulated-list-mode-map)
2024     (define-key map "v" 'Buffer-menu-select)
2025     (define-key map "2" 'Buffer-menu-2-window)
2026     (define-key map "1" 'Buffer-menu-1-window)
2027     (define-key map "f" 'Buffer-menu-this-window)
2028     (define-key map "e" 'Buffer-menu-this-window)
2029     (define-key map "\C-m" 'elpher-menu-this-window)
2030     (define-key map "o" 'elpher-menu-other-window)
2031     (define-key map "\C-o" 'elpher-menu-switch-other-window)
2032     (define-key map "d" 'Buffer-menu-delete)
2033     (define-key map "k" 'Buffer-menu-delete)
2034     (define-key map "\C-k" 'Buffer-menu-delete)
2035     (define-key map "\C-d" 'Buffer-menu-delete-backwards)
2036     (define-key map "x" 'Buffer-menu-execute)
2037     (define-key map " " 'next-line)
2038     (define-key map "\177" 'Buffer-menu-backup-unmark)
2039     (define-key map "u" 'Buffer-menu-unmark)
2040     (define-key map "m" 'Buffer-menu-mark)
2041     (define-key map "b" 'Buffer-menu-bury)
2042     (define-key map (kbd "M-s a C-s")   'Buffer-menu-isearch-buffers)
2043     (define-key map (kbd "M-s a M-C-s") 'Buffer-menu-isearch-buffers-regexp)
2044     (define-key map (kbd "M-s a C-o") 'Buffer-menu-multi-occur)
2045     (define-key map [mouse-2] 'Buffer-menu-mouse-select)
2046     (define-key map [follow-link] 'mouse-face)
2047     (define-key map [menu-bar elpher-menu-mode] (cons (purecopy "Elpher-Menu") menu-map))
2048     (bindings--define-key menu-map [quit]
2049       '(menu-item "Quit" quit-window
2050                  :help "Remove the elpher menu from the display"))
2051     (bindings--define-key menu-map [rev]
2052       '(menu-item "Refresh" revert-buffer
2053                  :help "Refresh the *Elpher Menu* buffer contents"))
2054     (bindings--define-key menu-map [s0] menu-bar-separator)
2055     (bindings--define-key menu-map [sel]
2056       '(menu-item "Select Marked" Buffer-menu-select
2057                  :help "Select this line's buffer; also display buffers marked with `>'"))
2058     (bindings--define-key menu-map [bm2]
2059       '(menu-item "Select Two" Buffer-menu-2-window
2060                  :help "Select this line's buffer, with previous buffer in second window"))
2061     (bindings--define-key menu-map [bm1]
2062       '(menu-item "Select Current" Buffer-menu-1-window
2063                  :help "Select this line's buffer, alone, in full frame"))
2064     (bindings--define-key menu-map [ow]
2065       '(menu-item "Select in Other Window" elpher-menu-other-window
2066                  :help "Select this line's buffer in other window, leaving buffer menu visible"))
2067     (bindings--define-key menu-map [tw]
2068       '(menu-item "Select in Current Window" elpher-menu-this-window
2069                  :help "Select this line's buffer in this window"))
2070     (bindings--define-key menu-map [s2] menu-bar-separator)
2071     (bindings--define-key menu-map [is]
2072       '(menu-item "Regexp Isearch Marked Buffers..." Buffer-menu-isearch-buffers-regexp
2073                  :help "Search for a regexp through all marked buffers using Isearch"))
2074     (bindings--define-key menu-map [ir]
2075       '(menu-item "Isearch Marked Buffers..." Buffer-menu-isearch-buffers
2076                  :help "Search for a string through all marked buffers using Isearch"))
2077     (bindings--define-key menu-map [mo]
2078       '(menu-item "Multi Occur Marked Buffers..." Buffer-menu-multi-occur
2079                  :help "Show lines matching a regexp in marked buffers using Occur"))
2080     (bindings--define-key menu-map [s3] menu-bar-separator)
2081     (bindings--define-key menu-map [by]
2082       '(menu-item "Bury" Buffer-menu-bury
2083                  :help "Bury the buffer listed on this line"))
2084     (bindings--define-key menu-map [ex]
2085       '(menu-item "Execute" Buffer-menu-execute
2086                  :help "Delete buffers marked with k commands"))
2087     (bindings--define-key menu-map [s4] menu-bar-separator)
2088     (bindings--define-key menu-map [delb]
2089       '(menu-item "Mark for Delete and Move Backwards" Buffer-menu-delete-backwards
2090                  :help "Mark buffer on this line to be deleted by x command and move up one line"))
2091     (bindings--define-key menu-map [del]
2092       '(menu-item "Mark for Delete" Buffer-menu-delete
2093                  :help "Mark buffer on this line to be deleted by x command"))
2094     (bindings--define-key menu-map [umk]
2095       '(menu-item "Unmark" Buffer-menu-unmark
2096                  :help "Cancel all requested operations on buffer on this line and move down"))
2097     (bindings--define-key menu-map [mk]
2098       '(menu-item "Mark" Buffer-menu-mark
2099                  :help "Mark buffer on this line for being displayed by v command"))
2100     map)
2101   "Local keymap for `elpher-menu-mode' buffers.")
2102
2103 (define-derived-mode elpher-menu-mode tabulated-list-mode "Elpher Menu"
2104   "Major mode for Elpher Menu buffers.
2105 The Elpher Menu is invoked by the command \\[elpher-menu]. When
2106 invoked with a prefix, the command also shows history items.
2107 Since history items are no longer showing in a buffer, many of
2108 the commands shown below will not work on them.
2109
2110 In Elpher Menu mode, the following commands are defined:
2111 \\<elpher-menu-mode-map>
2112 \\[quit-window]    Remove the Buffer Menu from the display.
2113 \\[tabulated-list-sort]    Sorts buffers according to the current
2114      column. With a numerical argument, sort by that column.
2115 \\[elpher-menu-this-window]  Select current line's buffer in place of the buffer menu.
2116 \\[elpher-menu-other-window]    Select that buffer in another window,
2117      so the Buffer Menu remains visible in its window.
2118 \\[elpher-menu-switch-other-window]  Make another window display that buffer.
2119 \\[Buffer-menu-mark]    Mark current line's buffer to be displayed.
2120 \\[Buffer-menu-select]    Select current line's buffer.
2121      Also show buffers marked with m, in other windows.
2122 \\[Buffer-menu-1-window]    Select that buffer in full-frame window.
2123 \\[Buffer-menu-2-window]    Select that buffer in one window, together with the
2124      buffer selected before this one in another window.
2125 \\[Buffer-menu-isearch-buffers]    Incremental search in the marked buffers.
2126 \\[Buffer-menu-isearch-buffers-regexp]  Isearch for regexp in the marked buffers.
2127 \\[Buffer-menu-multi-occur] Show lines matching regexp in the marked buffers.
2128 \\[Buffer-menu-delete]  Mark that buffer to be deleted, and move down.
2129 \\[Buffer-menu-delete-backwards]  Mark that buffer to be deleted, and move up.
2130 \\[Buffer-menu-execute]    Delete or save marked buffers.
2131 \\[Buffer-menu-unmark]    Remove all marks from current line.
2132      With prefix argument, also move up one line.
2133 \\[Buffer-menu-backup-unmark]  Back up a line and remove marks.
2134 \\[revert-buffer]    Update the list of buffers.
2135 \\[Buffer-menu-bury]    Bury the buffer listed on this line."
2136   (add-hook 'tabulated-list-revert-hook 'elpher-menu-refresh nil t))
2137
2138 (defun elpher-menu-this-window ()
2139   "Select this line’s buffer in this window.
2140 Switch to the buffer, if possible. If there is no buffer, chances
2141 are that we're looking at a history item. Let's visit the item
2142 instead of complaining that their buffers have been killed."
2143   (interactive)
2144   (elpher-menu-handle-buffer-or-data 'switch-to-buffer))
2145
2146 (defun elpher-menu-other-window ()
2147   "Select this line’s buffer in other window, leaving buffer menu visible."
2148   (interactive)
2149   (elpher-menu-handle-buffer-or-data 'switch-to-buffer-other-window))
2150
2151 (defun elpher-menu-switch-other-window ()
2152   "Make the other window select this line's buffer.
2153 The current window remains selected."
2154   (interactive)
2155   (elpher-menu-handle-buffer-or-data
2156    (lambda (buf) (display-buffer buf t))))
2157
2158 (defun elpher-menu-handle-buffer-or-data (buffer-func)
2159   "Handle an item in `elpher-menu-mode'.
2160 Determine the entry ID of the Tabulated List entry at point. If
2161 ID is a buffer, invoke BUFFER-FUNC on it. Otherwise, ID is a
2162 list (BUFFER FUNC ARGS...). Switch to BUFFER using BUFFER-FUNC
2163 and apply FUNC to ARGS."
2164   (let ((data (tabulated-list-get-id)))
2165     (cond ((bufferp data)
2166            (funcall buffer-func data))
2167           ((and (listp data)
2168                 (buffer-live-p (nth 0 data))
2169                 (fboundp (nth 1 data)))
2170            (funcall buffer-func (nth 0 data))
2171            (apply (nth 1 data) (nthcdr 2 data)))
2172           (t
2173            (error "There's no entry on this line of the menu")))))
2174
2175 (defvar elpher-title nil)
2176
2177 (defun elpher-find-title ()
2178   "Return the first heading1."
2179   (if elpher-title
2180       elpher-title
2181     (let ((start (text-property-any
2182                   (point-min) (point-max)
2183                   'face 'elpher-gemini-heading1)))
2184       (when start
2185         (save-excursion
2186           (goto-char start)
2187           (setq-local elpher-title
2188                       (buffer-substring-no-properties
2189                        start (line-end-position))))))))
2190
2191 (defun elpher-menu-refresh (&optional arg)
2192   "Refresh the list of buffers.
2193 With an optional argument, add all the history items, too. Note
2194 that there are no buffers for history items so many of the buffer
2195 menu commands won't work on them."
2196     (setq tabulated-list-format
2197           (vector '("T" 1 t)
2198                   '("Name" 30 t)
2199                   '("URL" 40 t))
2200           tabulated-list-sort-key nil)
2201     ;; Collect info for each buffer we're interested in.
2202     (let (entries)
2203       (dolist (buf (buffer-list))
2204         (with-current-buffer buf
2205           (when (memq major-mode '(elpher-mode eww-mode gemini-mode))
2206             (if arg
2207                 (setq entries (nconc (elpher-menu-refresh-history) entries))
2208               (push (elpher-menu-refresh-current) entries)))))
2209       (setq tabulated-list-entries (nreverse entries)))
2210     (tabulated-list-init-header))
2211
2212 (defun elpher-menu-refresh-current ()
2213   "Returns an item for `elpher-menu-refresh'
2214 based on the current buffer.
2215
2216 An item is a list (BUFFER VECTOR) where BUFFER is the buffer this
2217 item refers to and VECTOR is what to display in the tabulated
2218 list established by `elpher-menu-refresh'. See
2219 `tabulated-list-format'."
2220   (list (current-buffer)
2221         (cond ((eq major-mode 'elpher-mode)
2222                (vector "G"
2223                        (or (elpher-find-title)
2224                            (elpher-page-display-string elpher-current-page)
2225                            (buffer-name))
2226                        (or (elpher-address-to-url
2227                             (elpher-page-address elpher-current-page))
2228                            "none")))
2229               ((eq major-mode 'gemini-mode)
2230                (vector "E"
2231                        (or (elpher-page-display-string elpher-current-page)
2232                            (buffer-name))
2233                        (or (elpher-address-to-url
2234                             (elpher-page-address elpher-current-page))
2235                            "none")))
2236               ((eq major-mode 'eww-mode)
2237                (vector "W"
2238                        (or (plist-get eww-data :title)
2239                            (buffer-name))
2240                        (or (eww-current-url)
2241                            "none"))))))
2242
2243 (defun elpher-menu-refresh-history ()
2244   "Return current entries for `elpher-menu-refresh'.
2245 This returns a list of items for the current buffer, based on the
2246 buffer's history.
2247
2248 An item is a list (BUFFER VECTOR) where BUFFER is the buffer this
2249 item refers to and VECTOR is what to display in the tabulated
2250 list established by `elpher-menu-refresh'. See
2251 `tabulated-list-format'."
2252   ;; Every section starts with the current page, followed by some
2253   ;; history items, and ends with the separator.
2254   (let ((separator (list nil
2255                          (vector "-"
2256                                  (make-string 25 ?-)
2257                                  (make-string 25 ?-)))))
2258     (cond ((eq major-mode 'elpher-mode)
2259            ;; A pair is (BUFFER-OR-DATA . PAGE) where BUFFER-OR-DTA is
2260            ;; the current buffer, if possible, or list (BUFFER FUNC
2261            ;; &rest ARGS) telling us which BUFFER to switch to, and
2262            ;; what function to call. The last item of elpher-history
2263            ;; has a nil page, so when that shows up, use the separator
2264            (mapcar (lambda (pair)
2265                      (if (cdr pair)
2266                          (list (car pair)
2267                                (vector "G"
2268                                        (or (elpher-page-display-string (cdr pair)) "?")
2269                                        (or (elpher-address-to-url
2270                                             (elpher-page-address (cdr pair))) "none")))
2271                        separator))
2272                    (cons (cons (current-buffer) elpher-current-page)
2273                          (mapcar (lambda (page)
2274                                    (cons (list (current-buffer) 'elpher-visit-page page)
2275                                          page))
2276                                  elpher-history))))
2277           ((eq major-mode 'gemini-mode)
2278            ;; No history means a list of one item. Add a separator.
2279            (list (list (current-buffer)
2280                        (vector "E"
2281                                (or (elpher-page-display-string elpher-current-page)
2282                                    (buffer-name))
2283                                (or (elpher-address-to-url
2284                                     (elpher-page-address elpher-current-page)))))
2285                  separator))
2286            ((eq major-mode 'eww-mode)
2287            ;; A pair is (BUFFER-OR-DATA . PAGE) where BUFFER-OR-DTA is
2288            ;; the current buffer, if possible, or list (BUFFER FUNC
2289            ;; &rest ARGS) telling us which BUFFER to switch to, and
2290            ;; what function to call. Add the separator at the end.
2291             (nconc (cons (list (current-buffer)
2292                                (vector "W"
2293                                        (or (plist-get eww-data :title) "none")
2294                                        (or (plist-get eww-data :url) "none")))
2295                          (mapcar (lambda (data)
2296                                    (list
2297                                     (list (current-buffer) 'eww-restore-history data)
2298                                     (vector "W"
2299                                             (or (plist-get data :title) "none")
2300                                             (or (plist-get data :url) "none"))))
2301                                  eww-history))
2302                    (list separator))))))
2303
2304 ;;; Main start procedure
2305 ;;
2306
2307 ;;;###autoload
2308 (defun elpher (&optional arg)
2309   "Start elpher with default landing page.
2310 The buffer used for Elpher sessions is determined by the value of
2311 ‘elpher-buffer-name’.  If there is already an Elpher session active in
2312 that buffer, Emacs will simply switch to it.  Otherwise, a new session
2313 will begin.  A numeric prefix arg (as in ‘C-u 42 M-x elpher RET’)
2314 switches to the session with that number, creating it if necessary.  A
2315 nonnumeric prefix arg means to create a new session.  Returns the
2316 buffer selected (or created)."
2317   (interactive "P")
2318   (let* ((name (default-value 'elpher-buffer-name))
2319          (buf (cond ((numberp arg)
2320                      (get-buffer-create (format "%s<%d>" name arg)))
2321                     (arg
2322                      (generate-new-buffer name))
2323                     (t
2324                      (get-buffer-create name)))))
2325     (pop-to-buffer-same-window buf)
2326     (unless (buffer-modified-p)
2327       (elpher-mode)
2328       (let ((start-page (elpher-make-page "Elpher Start Page"
2329                                           (elpher-make-special-address 'start))))
2330         (elpher-visit-page start-page))
2331       "Started Elpher."))); Otherwise (elpher) evaluates to start page string.
2332
2333 ;;; elpher.el ends here