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