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