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