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