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