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