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