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