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