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