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