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