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