eb888b6535f880abb7a433173a34b8ad32bc0a7c
[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 (also next 2 lines)
632        (setq-local xterm-color--current-fg nil)
633        (setq-local xterm-color--current-bg nil)
634        (setq-local network-security-level
635                    (default-value 'network-security-level))
636        (erase-buffer)
637        (elpher-update-header)
638        ,@args)))
639
640 (defun elpher-buffer-message (string &optional line)
641   "Replace first line in elpher buffer with STRING.
642 If LINE is non-nil, replace that line instead."
643   (with-current-buffer elpher-buffer-name
644     (let ((inhibit-read-only t))
645       (goto-char (point-min))
646       (if line
647           (forward-line line))
648       (let ((data (match-data)))
649         (unwind-protect
650             (progn
651               (re-search-forward "^.*$")
652               (replace-match string))
653           (set-match-data data))))))
654
655
656 ;;; Text Processing
657 ;;
658
659 (defvar elpher-user-coding-system nil
660   "User-specified coding system to use for decoding text responses.")
661
662 (defun elpher-decode (string)
663   "Decode STRING using autodetected or user-specified coding system."
664   (decode-coding-string string
665                         (if elpher-user-coding-system
666                             elpher-user-coding-system
667                           (detect-coding-string string t))))
668
669 (defun elpher-preprocess-text-response (string)
670   "Preprocess text selector response contained in STRING.
671 This involes decoding the character representation, and clearing
672 away CRs and any terminating period."
673   (elpher-decode (replace-regexp-in-string "\n\\.\n$" "\n"
674                                            (replace-regexp-in-string "\r" "" string))))
675
676 ;;; Buttonify urls
677
678 (defconst elpher-url-regex
679   "\\([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_~?/@|#-]\\)?\\)?"
680   "Regexp used to locate and buttonify URLs in text files loaded by elpher.")
681
682 (defun elpher-buttonify-urls (string)
683   "Turn substrings which look like urls in STRING into clickable buttons."
684   (with-temp-buffer
685     (insert string)
686     (goto-char (point-min))
687     (while (re-search-forward elpher-url-regex nil t)
688       (let ((page (elpher-page-from-url (substring-no-properties (match-string 0)))))
689         (make-text-button (match-beginning 0)
690                           (match-end 0)
691                           'elpher-page  page
692                           'action #'elpher-click-link
693                           'follow-link t
694                           'help-echo #'elpher--page-button-help
695                           'face 'button)))
696     (buffer-string)))
697
698 ;;; ANSI colors or XTerm colors (application and filtering)
699
700 (or (require 'xterm-color nil t)
701     (require 'ansi-color))
702
703 (defalias 'elpher-color-filter-apply
704   (if (fboundp 'xterm-color-filter)
705       (lambda (s)
706         (let ((_xterm-color-render nil))
707           (xterm-color-filter s)))
708     #'ansi-color-filter-apply)
709   "A function to filter out ANSI escape sequences.")
710
711 (defalias 'elpher-color-apply
712   (if (fboundp 'xterm-color-filter)
713       #'xterm-color-filter
714     #'ansi-color-apply)
715   "A function to apply ANSI escape sequences.")
716
717 ;;; Processing text for display
718
719 (defun elpher-process-text-for-display (string)
720   "Perform any desired processing of STRING prior to display as text.
721 Currently includes buttonifying URLs and processing ANSI escape codes."
722   (elpher-buttonify-urls (if elpher-filter-ansi-from-text
723                              (elpher-color-filter-apply string)
724                            (elpher-color-apply string))))
725
726
727 ;;; Network error reporting
728 ;;
729
730 (defun elpher-network-error (address error)
731   "Display ERROR message following unsuccessful negotiation with ADDRESS.
732 ERROR can be either an error object or a string."
733   (elpher-with-clean-buffer
734    (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
735            "When attempting to retrieve " (elpher-address-to-url address) ":\n"
736            (if (stringp error) error (error-message-string error)) "\n"
737            (propertize "\n----------------\n\n" 'face 'error)
738            "Press 'u' to return to the previous page.")))
739
740
741 ;;; General network communication
742 ;;
743
744 (defvar elpher-network-timer nil
745   "Timer used for network connections.")
746
747 (defvar elpher-use-tls nil
748   "If non-nil, use TLS to communicate with gopher servers.")
749
750 (defvar elpher-client-certificate nil
751   "If non-nil, contains client certificate details to use for TLS connections.")
752
753 (defun elpher-process-cleanup ()
754   "Immediately shut down any extant elpher process and timers."
755   (let ((p (get-process "elpher-process")))
756     (if p (delete-process p)))
757   (if (timerp elpher-network-timer)
758       (cancel-timer elpher-network-timer)))
759
760 (defun elpher-make-network-timer (thunk)
761   "Create a timer to run the THUNK after `elpher-connection-timeout' seconds.
762 This is just a wraper around `run-at-time' which additionally sets the
763 buffer-local variable `elpher-network-timer' to allow
764 `elpher-process-cleanup' to also clear the timer."
765   (let ((timer (run-at-time elpher-connection-timeout nil thunk)))
766     (setq-local elpher-network-timer timer)
767     timer))
768
769 (defun elpher-get-host-response (address default-port query-string response-processor
770                                          &optional use-tls force-ipv4)
771   "Generic function for retrieving data from ADDRESS.
772
773 When ADDRESS lacks a specific port, DEFAULT-PORT is used instead.
774 QUERY-STRING is a string sent to the host specified by ADDRESS to
775 illicet a response.  This response is passed as an argument to the
776 function RESPONSE-PROCESSOR.
777
778 If non-nil, USE-TLS specifies that the connection is to be made over
779 TLS.  If set to gemini, the certificate verification will be disabled
780 unless `elpher-gemini-TLS-cert-checks' is non-nil.
781
782 If non-nil, FORCE-IPV4 causes the network connection to be made over
783 ipv4 only.  (The default behaviour when this is not set depends on
784 the host operating system and the local network capabilities.)"
785   (if (and use-tls (not (gnutls-available-p)))
786       (error "Use of TLS requires Emacs to be compiled with GNU TLS support")
787     (unless (< (elpher-address-port address) 65536)
788       (error "Cannot establish network connection: port number > 65536"))
789     (when (and (eq use-tls 'gemini) (not elpher-gemini-TLS-cert-checks))
790       (setq-local network-security-level 'low)
791       (setq-local gnutls-verify-error nil))
792     (condition-case nil
793         (let* ((kill-buffer-query-functions nil)
794                (port (elpher-address-port address))
795                (host (elpher-address-host address))
796                (service (if (> port 0) port default-port))
797                (response-string-parts nil)
798                (bytes-received 0)
799                (hkbytes-received 0)
800                (socks (or elpher-socks-always (string-suffix-p ".onion" host)))
801                (gnutls-params (list :type 'gnutls-x509pki
802                                     :hostname host
803                                     :keylist
804                                     (elpher-get-current-keylist address)))
805                (timer (elpher-make-network-timer
806                                    (lambda ()
807                                      (elpher-process-cleanup)
808                                      (cond
809                                         ; Try again with IPv4
810                                       ((not (or elpher-ipv4-always force-ipv4 socks))
811                                        (message "Connection timed out.  Retrying with IPv4.")
812                                        (elpher-get-host-response address default-port
813                                                                  query-string
814                                                                  response-processor
815                                                                  use-tls t))
816                                       ((and use-tls
817                                             (not (eq use-tls 'gemini))
818                                             (or elpher-auto-disengage-TLS
819                                                 (y-or-n-p
820                                                  "TLS connetion failed.  Disable TLS mode and retry? ")))
821                                        (setq elpher-use-tls nil)
822                                        (elpher-get-host-response address default-port
823                                                                  query-string
824                                                                  response-processor
825                                                                  nil force-ipv4))
826                                       (t
827                                        (elpher-network-error address "Connection time-out."))))))
828                (proc (if socks (socks-open-network-stream "elpher-process" nil host service)
829                        (make-network-process :name "elpher-process"
830                                              :host host
831                                              :family (and (or force-ipv4
832                                                               elpher-ipv4-always)
833                                                           'ipv4)
834                                              :service service
835                                              :buffer nil
836                                              :nowait t
837                                              :tls-parameters
838                                              (and use-tls
839                                                   (cons 'gnutls-x509pki
840                                                         (apply #'gnutls-boot-parameters
841                                                                gnutls-params)))))))
842           (setq elpher-network-timer timer)
843           (set-process-coding-system proc 'binary 'binary)
844           (set-process-query-on-exit-flag proc nil)
845           (elpher-buffer-message (concat "Connecting to " host "..."
846                                          " (press 'u' to abort)"))
847           (set-process-filter proc
848                               (lambda (_proc string)
849                                 (when timer
850                                   (cancel-timer timer)
851                                   (setq timer nil))
852                                 (setq bytes-received (+ bytes-received (length string)))
853                                 (let ((new-hkbytes-received (/ bytes-received 102400)))
854                                   (when (> new-hkbytes-received hkbytes-received)
855                                     (setq hkbytes-received new-hkbytes-received)
856                                     (elpher-buffer-message
857                                      (concat "("
858                                              (number-to-string (/ hkbytes-received 10.0))
859                                              " MB read)")
860                                      1)))
861                                 (setq response-string-parts
862                                       (cons string response-string-parts))))
863           (set-process-sentinel proc
864                                 (lambda (proc event)
865                                   (when timer
866                                     (cancel-timer timer))
867                                   (condition-case the-error
868                                       (cond
869                                        ((string-prefix-p "open" event)    ; request URL
870                                         (elpher-buffer-message
871                                          (concat "Connected to " host ". Receiving data..."
872                                                  " (press 'u' to abort)"))
873                                         (let ((inhibit-eol-conversion t))
874                                           (process-send-string proc query-string)))
875                                        ((string-prefix-p "deleted" event)) ; do nothing
876                                        ((and (not response-string-parts)
877                                              (not (or elpher-ipv4-always force-ipv4 socks)))
878                                         ; Try again with IPv4
879                                         (message "Connection failed. Retrying with IPv4.")
880                                         (elpher-get-host-response address default-port
881                                                                   query-string
882                                                                   response-processor
883                                                                   use-tls t))
884                                        (response-string-parts
885                                         (elpher-with-clean-buffer
886                                          (insert "Data received.  Rendering..."))
887                                         (funcall response-processor
888                                                  (apply #'concat (reverse response-string-parts)))
889                                         (elpher-restore-pos))
890                                        (t
891                                         (error "No response from server")))
892                                     (error
893                                      (elpher-network-error address the-error)))))
894           (when socks
895             (if use-tls (apply #'gnutls-negotiate :process proc gnutls-params))
896             (funcall (process-sentinel proc) proc "open\n")))
897       (error
898        (elpher-process-cleanup)
899        (error "Error initiating connection to server")))))
900
901
902 ;;; Client-side TLS Certificate Management
903 ;;
904
905 (defun elpher-generate-certificate (common-name key-file cert-file &optional temporary)
906   "Generate a key and a self-signed client TLS certificate using openssl.
907
908 The Common Name field of the certificate is set to COMMON-NAME.  The
909 arguments KEY-FILE and CERT-FILE should contain the absolute paths of
910 the key and certificate files to write.
911
912 If TEMPORARY is non-nil, the certificate will be given an exporation
913 period of one day, and the key and certificate files will be deleted
914 when the certificate is no longer needed for the current session.
915
916 Otherwise, the certificate will be given a 100 year expiration period
917 and the files will not be deleted.
918
919 The function returns a list containing the current host name, the
920 temporary flag, and the key and cert file names in the form required
921 by `gnutls-boot-parameters`."
922   (let ((exp-key-file (expand-file-name key-file))
923         (exp-cert-file (expand-file-name cert-file)))
924     (condition-case nil
925         (progn
926           (call-process elpher-openssl-command nil nil nil
927                         "req" "-x509" "-newkey" "rsa:2048"
928                         "-days" (if temporary "1" "36500")
929                         "-nodes"
930                         "-subj" (concat "/CN=" common-name)
931                         "-keyout" exp-key-file
932                         "-out" exp-cert-file)
933           (list (elpher-address-host (elpher-page-address elpher-current-page))
934                 temporary exp-key-file exp-cert-file))
935       (error
936        (message "Check that openssl is installed, or customize `elpher-openssl-command`.")
937        (error "Program 'openssl', required for certificate generation, not found")))))
938
939 (defun elpher-generate-throwaway-certificate ()
940   "Generate and return details of a throwaway certificate.
941 The key and certificate files will be deleted when they are no
942 longer needed for this session."
943   (let* ((file-base (make-temp-name "elpher"))
944          (key-file (concat temporary-file-directory file-base ".key"))
945          (cert-file (concat temporary-file-directory file-base ".crt")))
946     (elpher-generate-certificate file-base key-file cert-file t)))
947
948 (defun elpher-generate-persistent-certificate (file-base common-name)
949   "Generate and return details of a persistent certificate.
950 The argument FILE-BASE is used as the base for the key and certificate
951 files, while COMMON-NAME specifies the common name field of the
952 certificate.
953
954 The key and certificate files are written to in `elpher-certificate-directory'."
955   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
956          (cert-file (concat elpher-certificate-directory file-base ".crt")))
957     (elpher-generate-certificate common-name key-file cert-file)))
958
959 (defun elpher-get-existing-certificate (file-base)
960   "Return a certificate object corresponding to an existing certificate.
961 It is assumed that the key files FILE-BASE.key and FILE-BASE.crt exist in
962 the directory `elpher-certificate-directory'."
963   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
964          (cert-file (concat elpher-certificate-directory file-base ".crt")))
965     (list (elpher-address-host (elpher-page-address elpher-current-page))
966           nil
967           (expand-file-name key-file)
968           (expand-file-name cert-file))))
969
970 (defun elpher-install-and-use-existing-certificate (key-file-src cert-file-src file-base)
971   "Install a key+certificate file pair in `elpher-certificate-directory'.
972 The strings KEY-FILE-SRC and CERT-FILE-SRC are the existing key and
973 certificate files to install.  The argument FILE-BASE is used as the
974 base for the installed key and certificate files."
975   (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
976          (cert-file (concat elpher-certificate-directory file-base ".crt")))
977     (if (or (file-exists-p key-file)
978             (file-exists-p cert-file))
979         (error "A certificate with base name %s is already installed" file-base))
980     (copy-file key-file-src key-file)
981     (copy-file cert-file-src cert-file)
982     (list (elpher-address-host (elpher-page-address elpher-current-page))
983           nil
984           (expand-file-name key-file)
985           (expand-file-name cert-file))))
986
987 (defun elpher-list-existing-certificates ()
988   "Return a list of the persistent certificates in `elpher-certificate-directory'."
989   (unless (file-directory-p elpher-certificate-directory)
990     (make-directory elpher-certificate-directory))
991   (mapcar
992    (lambda (file)
993      (file-name-sans-extension file))
994    (directory-files elpher-certificate-directory nil "\\.key$")))
995
996 (defun elpher-forget-current-certificate ()
997   "Causes any current certificate to be forgotten.)
998 In the case of throwaway certificates, the key and certificate files
999 are also deleted."
1000   (interactive)
1001   (when elpher-client-certificate
1002     (unless (and (called-interactively-p 'any)
1003                  (not (y-or-n-p (concat "Really forget client certificate? "
1004                                         "(Throwaway certificates will be deleted.)"))))
1005       (when (cadr elpher-client-certificate)
1006         (delete-file (elt elpher-client-certificate 2))
1007         (delete-file (elt elpher-client-certificate 3)))
1008       (setq elpher-client-certificate nil)
1009       (if (called-interactively-p 'any)
1010           (message "Client certificate forgotten.")))))
1011
1012 (defun elpher-get-current-keylist (address)
1013   "Retrieve the `gnutls-boot-parameters'-compatable keylist.
1014
1015 This is obtained from the client certificate described by
1016 `elpher-current-certificate', if one is available and the host for
1017 that certificate matches the host in ADDRESS.
1018
1019 If `elpher-current-certificate' is non-nil, and its host name doesn't
1020 match that of ADDRESS, the certificate is forgotten."
1021   (if elpher-client-certificate
1022       (if (string= (car elpher-client-certificate)
1023                    (elpher-address-host address))
1024           (list (cddr elpher-client-certificate))
1025         (elpher-forget-current-certificate)
1026         (message "Disabling client certificate for new host")
1027         nil)
1028     nil))
1029
1030
1031 ;;; Gopher selector retrieval
1032 ;;
1033
1034 (defun elpher-get-gopher-response (address renderer)
1035   "Get response string from gopher server at ADDRESS and render using RENDERER."
1036   (elpher-get-host-response address 70
1037                             (concat (elpher-gopher-address-selector address) "\r\n")
1038                             renderer
1039                             (or (string= (elpher-address-protocol address) "gophers")
1040                                 elpher-use-tls)))
1041
1042 (defun elpher-get-gopher-page (renderer)
1043   "Getter function for gopher pages.
1044 The RENDERER procedure is used to display the contents of the page
1045 once they are retrieved from the gopher server."
1046   (let* ((address (elpher-page-address elpher-current-page))
1047          (content (elpher-get-cached-content address)))
1048     (if (and content (funcall renderer nil))
1049         (elpher-with-clean-buffer
1050          (insert content)
1051          (elpher-restore-pos))
1052       (elpher-with-clean-buffer
1053        (insert "LOADING... (use 'u' to cancel)\n"))
1054       (condition-case the-error
1055           (elpher-get-gopher-response address renderer)
1056         (error
1057          (elpher-network-error address the-error))))))
1058
1059 ;; Index rendering
1060
1061 (defun elpher-insert-margin (&optional type-name)
1062   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
1063   (if type-name
1064       (progn
1065         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
1066                         (concat
1067                          (propertize "[" 'face 'elpher-margin-brackets)
1068                          (propertize type-name 'face 'elpher-margin-key)
1069                          (propertize "]" 'face 'elpher-margin-brackets))))
1070         (insert " "))
1071     (insert (make-string elpher-margin-width ?\s))))
1072
1073 (defun elpher--page-button-help (_window buffer pos)
1074   "Function called by Emacs to generate mouse-over text.
1075 The arguments specify the BUFFER and the POS within the buffer of the item
1076 for which help is required.  The function returns the help to be
1077 displayed.  The _WINDOW argument is currently unused."
1078   (with-current-buffer buffer
1079     (let ((button (button-at pos)))
1080       (when button
1081         (let* ((page (button-get button 'elpher-page))
1082                (address (elpher-page-address page)))
1083           (format "mouse-1, RET: open '%s'" (elpher-address-to-url address)))))))
1084
1085 (defun elpher-insert-index-record (display-string &optional address)
1086   "Function to insert an index record into the current buffer.
1087 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
1088 If ADDRESS is not supplied or nil the record is rendered as an
1089 'information' line."
1090   (let* ((type (if address (elpher-address-type address) nil))
1091          (type-map-entry (cdr (assoc type elpher-type-map))))
1092     (if type-map-entry
1093         (let* ((margin-code (elt type-map-entry 2))
1094                (face (elt type-map-entry 3))
1095                (filtered-display-string (elpher-color-filter-apply display-string))
1096                (page (elpher-make-page filtered-display-string address)))
1097           (elpher-insert-margin margin-code)
1098           (insert-text-button filtered-display-string
1099                               'face face
1100                               'elpher-page page
1101                               'action #'elpher-click-link
1102                               'follow-link t
1103                               'help-echo #'elpher--page-button-help))
1104       (pcase type
1105         ('nil ;; Information
1106          (elpher-insert-margin)
1107          (let ((propertized-display-string
1108                 (propertize display-string 'face 'elpher-info)))
1109            (insert (elpher-process-text-for-display propertized-display-string))))
1110         (`(gopher ,selector-type) ;; Unknown
1111          (elpher-insert-margin (concat (char-to-string selector-type) "?"))
1112          (insert (propertize display-string
1113                              'face 'elpher-unknown)))))
1114     (insert "\n")))
1115
1116 (defun elpher-click-link (button)
1117   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
1118   (let ((page (button-get button 'elpher-page)))
1119     (elpher-visit-page page)))
1120
1121 (defun elpher-render-index (data &optional _mime-type-string)
1122   "Render DATA as an index.  MIME-TYPE-STRING is unused."
1123   (elpher-with-clean-buffer
1124    (if (not data)
1125        t
1126      (let ((data-processed (elpher-preprocess-text-response data)))
1127        (dolist (line (split-string data-processed "\n"))
1128          (ignore-errors
1129            (unless (= (length line) 0)
1130              (let* ((type (elt line 0))
1131                     (fields (split-string (substring line 1) "\t"))
1132                     (display-string (elt fields 0))
1133                     (selector (elt fields 1))
1134                     (host (elt fields 2))
1135                     (port (if (elt fields 3)
1136                               (string-to-number (elt fields 3))
1137                             nil))
1138                     (address (elpher-make-gopher-address type selector host port)))
1139                (elpher-insert-index-record display-string address))))))
1140      (elpher-cache-content (elpher-page-address elpher-current-page)
1141                            (buffer-string)))))
1142
1143 ;; Text rendering
1144
1145 (defun elpher-render-text (data &optional _mime-type-string)
1146   "Render DATA as text.  MIME-TYPE-STRING is unused."
1147   (elpher-with-clean-buffer
1148    (if (not data)
1149        t
1150      (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
1151      (elpher-cache-content
1152       (elpher-page-address elpher-current-page)
1153       (buffer-string)))))
1154
1155 ;; Image retrieval
1156
1157 (defun elpher-render-image (data &optional _mime-type-string)
1158   "Display DATA as image.  MIME-TYPE-STRING is unused."
1159   (if (not data)
1160       nil
1161     (if (display-images-p)
1162         (let* ((image (create-image
1163                        data
1164                        nil t)))
1165           (if (not image)
1166               (error "Unsupported image format")
1167             (let ((window (get-buffer-window elpher-buffer-name)))
1168               (when window
1169                 (setf (image-property image :max-width) (window-body-width window t))
1170                 (setf (image-property image :max-height) (window-body-height window t))))
1171             (elpher-with-clean-buffer
1172              (insert-image image)
1173              (elpher-restore-pos))))
1174       (elpher-render-download data))))
1175
1176 ;; Search retrieval and rendering
1177
1178 (defun elpher-get-gopher-query-page (renderer)
1179   "Getter for gopher addresses requiring input.
1180 The response is rendered using the rendering function RENDERER."
1181   (let* ((address (elpher-page-address elpher-current-page))
1182          (content (elpher-get-cached-content address))
1183          (aborted t))
1184     (if (and content (funcall renderer nil))
1185         (elpher-with-clean-buffer
1186          (insert content)
1187          (elpher-restore-pos)
1188          (message "Displaying cached search results.  Reload to perform a new search."))
1189       (unwind-protect
1190           (let* ((query-string (read-string "Query: "))
1191                  (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
1192                  (search-address (elpher-make-gopher-address ?1
1193                                                              query-selector
1194                                                              (elpher-address-host address)
1195                                                              (elpher-address-port address)
1196                                                              (equal (elpher-address-type address) "gophers"))))
1197             (setq aborted nil)
1198
1199             (elpher-with-clean-buffer
1200              (insert "LOADING RESULTS... (use 'u' to cancel)"))
1201             (elpher-get-gopher-response search-address renderer))
1202         (if aborted
1203             (elpher-visit-previous-page))))))
1204
1205 ;; Raw server response rendering
1206
1207 (defun elpher-render-raw (data &optional mime-type-string)
1208   "Display raw DATA in buffer.  MIME-TYPE-STRING is also displayed if provided."
1209   (if (not data)
1210       nil
1211     (elpher-with-clean-buffer
1212      (when mime-type-string
1213        (insert "MIME type specified by server: '" mime-type-string "'\n"))
1214      (insert data)
1215      (goto-char (point-min)))
1216     (message "Displaying raw server response.  Reload or redraw to return to standard view.")))
1217
1218 ;; File save "rendering"
1219
1220 (defun elpher-render-download (data &optional _mime-type-string)
1221   "Save DATA to file.  MIME-TYPE-STRING is unused."
1222   (if (not data)
1223       nil
1224     (let* ((address (elpher-page-address elpher-current-page))
1225            (selector (if (elpher-address-gopher-p address)
1226                          (elpher-gopher-address-selector address)
1227                        (elpher-address-filename address))))
1228       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1229       (let* ((filename-proposal (file-name-nondirectory selector))
1230              (filename (read-file-name "Download complete. Save file as: "
1231                                        nil nil nil
1232                                        (if (> (length filename-proposal) 0)
1233                                            filename-proposal
1234                                          "download.file"))))
1235         (let ((coding-system-for-write 'binary))
1236           (with-temp-file filename
1237             (insert data)))
1238         (message (format "Saved to file %s." filename))))))
1239
1240 ;; HTML rendering
1241
1242 (defun elpher-render-html (data &optional _mime-type-string)
1243   "Render DATA as HTML using shr.  MIME-TYPE-STRING is unused."
1244   (elpher-with-clean-buffer
1245    (if (not data)
1246        t
1247      (let ((dom (with-temp-buffer
1248                   (insert data)
1249                   (libxml-parse-html-region (point-min) (point-max)))))
1250        (shr-insert-document dom)))))
1251
1252 ;; Gemini page retrieval
1253
1254 (defvar elpher-gemini-redirect-chain)
1255
1256 (defun elpher-get-gemini-response (address renderer)
1257   "Get response string from gemini server at ADDRESS and render using RENDERER."
1258   (elpher-get-host-response address 1965
1259                             (concat (elpher-address-to-url address) "\r\n")
1260                             (lambda (response-string)
1261                               (elpher-process-gemini-response response-string renderer))
1262                             'gemini))
1263
1264 (defun elpher-parse-gemini-response (response)
1265   "Parse the RESPONSE string and return a list of components.
1266 The list is of the form (code meta body).  A response of nil implies
1267 that the response was malformed."
1268   (let ((header-end-idx (string-match "\r\n" response)))
1269     (if header-end-idx
1270         (let ((header (string-trim (substring response 0 header-end-idx)))
1271               (body (substring response (+ header-end-idx 2))))
1272           (if (>= (length header) 2)
1273               (let ((code (substring header 0 2))
1274                     (meta (string-trim (substring header 2))))
1275                 (list code meta body))
1276             (error "Malformed response: No response status found in header %s" header)))
1277       (error "Malformed response: No CRLF-delimited header found in response %s" response))))
1278
1279 (defun elpher-process-gemini-response (response-string renderer)
1280   "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
1281   (let ((response-components (elpher-parse-gemini-response response-string)))
1282     (let ((response-code (elt response-components 0))
1283           (response-meta (elt response-components 1))
1284           (response-body (elt response-components 2)))
1285       (pcase (elt response-code 0)
1286         (?1 ; Input required
1287          (elpher-with-clean-buffer
1288           (insert "Gemini server is requesting input."))
1289          (let* ((query-string
1290                  (if (eq (elt response-code 1) ?1)
1291                      (read-passwd (concat response-meta ": "))
1292                    (read-string (concat response-meta ": "))))
1293                 (query-address (seq-copy (elpher-page-address elpher-current-page)))
1294                 (old-fname (url-filename query-address)))
1295            (setf (url-filename query-address)
1296                  (concat old-fname "?" (url-build-query-string `((,query-string)))))
1297            (elpher-get-gemini-response query-address renderer)))
1298         (?2 ; Normal response
1299          (funcall renderer response-body response-meta))
1300         (?3 ; Redirect
1301          (message "Following redirect to %s" response-meta)
1302          (if (>= (length elpher-gemini-redirect-chain) 5)
1303              (error "More than 5 consecutive redirects followed"))
1304          (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
1305            (if (member redirect-address elpher-gemini-redirect-chain)
1306                (error "Redirect loop detected"))
1307            (if (not (eq (elpher-address-type redirect-address) 'gemini))
1308                (error "Server tried to automatically redirect to non-gemini URL: %s"
1309                       response-meta))
1310            (elpher-page-set-address elpher-current-page redirect-address)
1311            (add-to-list 'elpher-gemini-redirect-chain redirect-address)
1312            (elpher-get-gemini-response redirect-address renderer)))
1313         (?4 ; Temporary failure
1314          (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
1315                 response-code response-meta))
1316         (?5 ; Permanent failure
1317          (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
1318                 response-code response-meta))
1319         (?6 ; Client certificate required
1320          (elpher-with-clean-buffer
1321           (if elpher-client-certificate
1322               (insert "Gemini server does not recognise the provided TLS certificate:\n\n")
1323             (insert "Gemini server is requesting a valid TLS certificate:\n\n"))
1324           (auto-fill-mode 1)
1325           (elpher-gemini-insert-text response-meta))
1326          (let ((chosen-certificate (elpher-choose-client-certificate)))
1327            (unless chosen-certificate
1328              (error "Gemini server requires a client certificate and none was provided"))
1329            (setq elpher-client-certificate chosen-certificate))
1330          (elpher-with-clean-buffer)
1331          (elpher-get-gemini-response (elpher-page-address elpher-current-page) renderer))
1332         (_other
1333          (error "Gemini server response unknown: %s %s"
1334                 response-code response-meta))))))
1335
1336 (defun elpher--read-answer-polyfill (question answers)
1337   "Polyfill for `read-answer' in Emacs 26.1.
1338 QUESTION is a string containing a question, and ANSWERS
1339 is a list of possible answers."
1340     (completing-read question (mapcar 'identity answers)))
1341
1342 (if (fboundp 'read-answer)
1343     (defalias 'elpher-read-answer 'read-answer)
1344   (defalias 'elpher-read-answer 'elpher--read-answer-polyfill))
1345
1346 (defun elpher-choose-client-certificate ()
1347   "Prompt for a client certificate to use to establish a TLS connection."
1348   (let* ((read-answer-short t))
1349     (pcase (read-answer "What do you want to do? "
1350                         '(("throwaway" ?t
1351                            "generate and use throw-away certificate")
1352                           ("persistent" ?p
1353                            "generate new or use existing persistent certificate")
1354                           ("abort" ?a
1355                            "stop immediately")))
1356       ("throwaway"
1357        (setq elpher-client-certificate (elpher-generate-throwaway-certificate)))
1358       ("persistent"
1359        (let* ((existing-certificates (elpher-list-existing-certificates))
1360               (file-base (completing-read
1361                           "Nickname for new or existing certificate (autocompletes, empty response aborts): "
1362                           existing-certificates)))
1363          (if (string-empty-p (string-trim file-base))
1364              nil
1365            (if (member file-base existing-certificates)
1366                (setq elpher-client-certificate
1367                      (elpher-get-existing-certificate file-base))
1368              (pcase (read-answer "Generate new certificate or install externally-generated one? "
1369                                  '(("new" ?n
1370                                     "generate new certificate")
1371                                    ("install" ?i
1372                                     "install existing certificate")
1373                                    ("abort" ?a
1374                                     "stop immediately")))
1375                ("new"
1376                 (let ((common-name (read-string "Common Name field for new certificate: "
1377                                                 file-base)))
1378                   (message "New key and self-signed certificate written to %s"
1379                            elpher-certificate-directory)
1380                   (elpher-generate-persistent-certificate file-base common-name)))
1381                ("install"
1382                 (let* ((cert-file (read-file-name "Certificate file: " nil nil t))
1383                        (key-file (read-file-name "Key file: " nil nil t)))
1384                   (message "Key and certificate installed in %s for future use"
1385                            elpher-certificate-directory)
1386                   (elpher-install-and-use-existing-certificate key-file
1387                                                                cert-file
1388                                                                file-base)))
1389                ("abort" nil))))))
1390       ("abort" nil))))
1391
1392 (defun elpher-get-gemini-page (renderer)
1393   "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1394   (let* ((address (elpher-page-address elpher-current-page))
1395          (content (elpher-get-cached-content address)))
1396     (condition-case the-error
1397         (if (and content (funcall renderer nil))
1398             (elpher-with-clean-buffer
1399              (insert content)
1400              (elpher-restore-pos))
1401           (elpher-with-clean-buffer
1402            (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1403           (setq elpher-gemini-redirect-chain nil)
1404           (elpher-get-gemini-response address renderer))
1405       (error
1406        (elpher-network-error address the-error)))))
1407
1408 (defun elpher-render-gemini (body &optional mime-type-string)
1409   "Render gemini response BODY with rendering MIME-TYPE-STRING."
1410   (if (not body)
1411       t
1412     (let* ((mime-type-string* (if (or (not mime-type-string)
1413                                       (string-empty-p mime-type-string))
1414                                   "text/gemini; charset=utf-8"
1415                                 mime-type-string))
1416            (mime-type-split (split-string mime-type-string* ";" t))
1417            (mime-type (string-trim (car mime-type-split)))
1418            (parameters (mapcar (lambda (s)
1419                                  (let ((key-val (split-string s "=")))
1420                                    (list (downcase (string-trim (car key-val)))
1421                                          (downcase (string-trim (cadr key-val))))))
1422                                (cdr mime-type-split))))
1423       (when (string-prefix-p "text/" mime-type)
1424         (setq body (decode-coding-string
1425                     body
1426                     (if (assoc "charset" parameters)
1427                         (intern (cadr (assoc "charset" parameters)))
1428                       'utf-8)))
1429         (setq body (replace-regexp-in-string "\r" "" body)))
1430       (pcase mime-type
1431         ((or "text/gemini" "")
1432          (elpher-render-gemini-map body parameters))
1433         ("text/html"
1434          (elpher-render-html body))
1435         ((pred (string-prefix-p "text/"))
1436          (elpher-render-gemini-plain-text body parameters))
1437         ((pred (string-prefix-p "image/"))
1438          (elpher-render-image body))
1439         (_other
1440          (elpher-render-download body))))))
1441
1442 (defun elpher-gemini-get-link-url (link-line)
1443   "Extract the url portion of LINK-LINE, a gemini map file link line.
1444 Returns nil in the event that the contents of the line following the
1445 => prefix are empty."
1446   (let ((l (split-string (substring link-line 2))))
1447     (if l
1448         (string-trim (elt l 0))
1449       nil)))
1450
1451 (defun elpher-gemini-get-link-display-string (link-line)
1452   "Extract the display string portion of LINK-LINE, a gemini map file link line.
1453 Return nil if this portion is not provided."
1454   (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1455          (idx (string-match "[ \t]" rest)))
1456     (and idx
1457          (elpher-color-filter-apply (string-trim (substring rest (+ idx 1)))))))
1458
1459 (defun elpher-collapse-dot-sequences (filename)
1460   "Collapse dot sequences in the (absolute) FILENAME.
1461 For instance, the filename \"/a/b/../c/./d\" will reduce to \"/a/c/d\""
1462   (let* ((path (split-string filename "/" t))
1463          (is-directory (string-match-p (rx (: (or "." ".." "/") line-end)) filename))
1464          (path-reversed-normalized
1465           (seq-reduce (lambda (a b)
1466                         (cond ((equal b "..") (cdr a))
1467                               ((equal b ".") a)
1468                               (t (cons b a))))
1469                       path nil))
1470          (path-normalized (reverse path-reversed-normalized)))
1471     (if path-normalized
1472         (concat "/" (string-join path-normalized "/") (and is-directory "/"))
1473       "/")))
1474
1475 (defun elpher-address-from-gemini-url (url)
1476   "Extract address from URL with defaults as per gemini map files.
1477 While there's obviously some redundancy here between this function and
1478 `elpher-address-from-url', gemini map file URLs require enough special
1479 treatment that a separate function is warranted."
1480   (let ((address (url-generic-parse-url url))
1481         (current-address (elpher-page-address elpher-current-page)))
1482     (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1483       (if (url-host address) ;if there is an explicit host, filenames are absolute
1484           (if (string-empty-p (url-filename address))
1485               (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1486         (setf (url-host address) (url-host current-address))
1487         (setf (url-fullness address) (url-host address)) ; set fullness to t if host is set
1488         (setf (url-portspec address) (url-portspec current-address)) ; (url-port) too slow!
1489         (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1490           (setf (url-filename address)
1491                 (concat (file-name-directory (url-filename current-address))
1492                         (url-filename address)))))
1493       (when (url-host address)
1494         (setf (url-host address) (puny-encode-domain (url-host address))))
1495       (unless (url-type address)
1496         (setf (url-type address) (url-type current-address)))
1497       (when (equal (url-type address) "gemini")
1498         (setf (url-filename address)
1499               (elpher-collapse-dot-sequences (url-filename address)))))
1500     (elpher-remove-redundant-ports address)))
1501
1502 (defun elpher-gemini-insert-link (link-line)
1503   "Insert link described by LINK-LINE into a text/gemini document."
1504   (let ((url (elpher-gemini-get-link-url link-line)))
1505     (when url
1506       (let* ((given-display-string (elpher-gemini-get-link-display-string link-line))
1507              (address (elpher-address-from-gemini-url url))
1508              (type (if address (elpher-address-type address) nil))
1509              (type-map-entry (cdr (assoc type elpher-type-map)))
1510              (fill-prefix (make-string (+ 1 (length elpher-gemini-link-string)) ?\s)))
1511         (when type-map-entry
1512           (insert elpher-gemini-link-string)
1513           (let* ((face (elt type-map-entry 3))
1514                  (display-string (or given-display-string
1515                                      (elpher-address-to-iri address)))
1516                  (page (elpher-make-page display-string
1517                                          address)))
1518             (insert-text-button display-string
1519                                 'face face
1520                                 'elpher-page page
1521                                 'action #'elpher-click-link
1522                                 'follow-link t
1523                                 'help-echo #'elpher--page-button-help))
1524           (newline))))))
1525
1526 (defun elpher-gemini-insert-header (header-line)
1527   "Insert header described by HEADER-LINE into a text/gemini document.
1528 The gemini map file line describing the header is given
1529 by HEADER-LINE."
1530   (when (string-match "^\\(#+\\)[ \t]*" header-line)
1531     (let* ((level (length (match-string 1 header-line)))
1532            (header (substring header-line (match-end 0)))
1533            (face (pcase level
1534                    (1 'elpher-gemini-heading1)
1535                    (2 'elpher-gemini-heading2)
1536                    (3 'elpher-gemini-heading3)
1537                    (_ 'default)))
1538            (fill-column (if (display-graphic-p)
1539                             (/ (* fill-column
1540                                   (font-get (font-spec :name (face-font 'default)) :size))
1541                                (font-get (font-spec :name (face-font face)) :size)) fill-column)))
1542       (unless (display-graphic-p)
1543         (insert (make-string level ?#) " "))
1544       (insert (propertize header
1545                           'face face
1546                           'gemini-heading t
1547                           'rear-nonsticky t))
1548       (newline))))
1549
1550 (defun elpher-gemini-insert-text (text-line)
1551   "Insert a plain non-preformatted TEXT-LINE into a text/gemini document.
1552 This function uses Emacs' auto-fill to wrap text sensibly to a maximum
1553 width defined by `elpher-gemini-max-fill-width'."
1554   (string-match
1555    (rx (: line-start
1556           (optional
1557            (group (or (: "*" (+ (any " \t")))
1558                       (: ">" (* (any " \t"))))))))
1559    text-line)
1560   (let* ((line-prefix (match-string 1 text-line))
1561          (processed-text-line
1562           (if line-prefix
1563               (cond ((string-prefix-p "*" line-prefix)
1564                      (concat
1565                       (replace-regexp-in-string "\\*"
1566                                                 elpher-gemini-bullet-string
1567                                                 (match-string 0 text-line))
1568                       (substring text-line (match-end 0))))
1569                     ((string-prefix-p ">" line-prefix)
1570                      (propertize text-line 'face 'elpher-gemini-quoted))
1571                     (t text-line))
1572             text-line))
1573          (fill-prefix (if line-prefix
1574                           (make-string (length (match-string 0 text-line)) ?\s)
1575                         nil)))
1576     (insert (elpher-process-text-for-display processed-text-line))
1577     (newline)))
1578
1579 (defun elpher-render-gemini-map (data _parameters)
1580   "Render DATA as a gemini map file, PARAMETERS is currently unused."
1581   (elpher-with-clean-buffer
1582    (auto-fill-mode 1)
1583    (let ((preformatted nil)
1584          (adaptive-fill-mode nil)) ;Prevent automatic setting of fill-prefix
1585      (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1586      (dolist (line (split-string data "\n"))
1587        (cond
1588         ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1589         (preformatted (insert (elpher-process-text-for-display
1590                                (propertize line 'face 'elpher-gemini-preformatted))
1591                               "\n"))
1592         ((string-prefix-p "=>" line)
1593          (elpher-gemini-insert-link line))
1594         ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1595         (t (elpher-gemini-insert-text line)))))
1596    (elpher-cache-content
1597     (elpher-page-address elpher-current-page)
1598     (buffer-string))))
1599
1600 (defun elpher-render-gemini-plain-text (data _parameters)
1601   "Render DATA as plain text file.  PARAMETERS is currently unused."
1602   (elpher-with-clean-buffer
1603    (insert (elpher-process-text-for-display data))
1604    (elpher-cache-content
1605     (elpher-page-address elpher-current-page)
1606     (buffer-string))))
1607
1608 (defun elpher-build-current-imenu-index ()
1609   "Build imenu index for current elpher buffer."
1610   (save-excursion
1611     (goto-char (point-min))
1612     (let ((match nil)
1613           (headers nil))
1614       (while (setq match (text-property-search-forward 'gemini-heading t t))
1615         (push (cons
1616                (buffer-substring-no-properties (prop-match-beginning match)
1617                                                (prop-match-end match))
1618                (prop-match-beginning match))
1619               headers))
1620       (reverse headers))))
1621
1622 ;; Finger page connection
1623
1624 (defun elpher-get-finger-page (renderer)
1625   "Opens a finger connection to the current page address.
1626 The result is rendered using RENDERER."
1627   (let* ((address (elpher-page-address elpher-current-page))
1628          (content (elpher-get-cached-content address)))
1629     (if (and content (funcall renderer nil))
1630         (elpher-with-clean-buffer
1631          (insert content)
1632          (elpher-restore-pos))
1633       (elpher-with-clean-buffer
1634        (insert "LOADING... (use 'u' to cancel)\n"))
1635       (condition-case the-error
1636           (let* ((kill-buffer-query-functions nil)
1637                  (user (let ((filename (elpher-address-filename address)))
1638                          (if (> (length filename) 1)
1639                              (substring filename 1)
1640                            (elpher-address-user address)))))
1641             (elpher-get-host-response address 79
1642                                       (concat user "\r\n")
1643                                       renderer))
1644         (error
1645          (elpher-network-error address the-error))))))
1646
1647
1648 ;; Telnet page connection
1649
1650 (defun elpher-get-telnet-page (renderer)
1651   "Opens a telnet connection to the current page address (RENDERER must be nil)."
1652   (when renderer
1653     (elpher-visit-previous-page)
1654     (error "Command not supported for telnet URLs"))
1655   (let* ((address (elpher-page-address elpher-current-page))
1656          (host (elpher-address-host address))
1657          (port (elpher-address-port address)))
1658     (elpher-visit-previous-page)
1659     (if (> port 0)
1660         (telnet host port)
1661       (telnet host))))
1662
1663
1664 ;; Other URL page opening
1665
1666 (defun elpher-get-other-url-page (renderer)
1667   "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1668   (when renderer
1669     (elpher-visit-previous-page)
1670     (error "Command not supported for general URLs"))
1671   (let* ((address (elpher-page-address elpher-current-page))
1672          (url (elpher-address-to-url address)))
1673     (elpher-visit-previous-page) ; Do first in case of non-local exits.
1674     (message "Opening URL...")
1675     (if elpher-open-urls-with-eww
1676         (browse-web url)
1677       (browse-url url))))
1678
1679 ;; File page
1680
1681 (defun elpher-get-file-page (renderer)
1682   "Getter which renders a local file using RENDERER.
1683 Assumes UTF-8 encoding for all text files."
1684   (let* ((address (elpher-page-address elpher-current-page))
1685          (filename (elpher-address-filename address)))
1686     (unless (file-exists-p filename)
1687       (elpher-visit-previous-page)
1688         (error "File not found"))
1689     (unless (file-readable-p filename)
1690       (elpher-visit-previous-page)
1691         (error "Could not read from file"))
1692     (let ((body (with-temp-buffer
1693        (let ((coding-system-for-read 'binary)
1694              (coding-system-for-write 'binary))
1695          (insert-file-contents-literally filename)
1696          (encode-coding-string (buffer-string) 'raw-text)))))
1697        (if renderer
1698            (funcall renderer body nil)
1699          (pcase (file-name-extension filename)
1700            ((or  "gmi" "gemini")
1701             (elpher-render-gemini-map (decode-coding-string body 'utf-8) nil))
1702            ((or "htm" "html")
1703             (elpher-render-html (decode-coding-string body 'utf-8)))
1704            ((or "txt" "")
1705             (elpher-render-text (decode-coding-string body 'utf-8)))
1706            ((or "jpg" "jpeg" "gif" "png" "bmp" "tif" "tiff")
1707             (elpher-render-image body))
1708            ((or "gopher" "gophermap")
1709             (elpher-render-index (elpher-decode body)))
1710            (_
1711             (elpher-render-download body))))
1712        (elpher-restore-pos))))
1713
1714
1715 ;; Welcome page retrieval
1716
1717 (defun elpher-get-welcome-page (renderer)
1718   "Getter which displays the welcome page (RENDERER must be nil)."
1719   (when renderer
1720     (elpher-visit-previous-page)
1721     (error "Command not supported for welcome page"))
1722   (elpher-with-clean-buffer
1723    (insert "     --------------------------------------------\n"
1724            "           Elpher Gopher and Gemini Client       \n"
1725            "                   version " elpher-version "\n"
1726            "     --------------------------------------------\n"
1727            "\n"
1728            "Default bindings:\n"
1729            "\n"
1730            " - TAB/Shift-TAB: next/prev item on current page\n"
1731            " - RET/mouse-1: open item under cursor\n"
1732            " - m: select an item on current page by name (autocompletes)\n"
1733            " - u/mouse-3/U: return to previous page or to the start page\n"
1734            " - g: go to a particular address (gopher, gemini, finger)\n"
1735            " - o/O: open a different address selector or the root menu of the current server\n"
1736            " - d/D: download item under cursor or current page\n"
1737            " - i/I: info on item under cursor or current page\n"
1738            " - c/C: copy URL representation of item under cursor or current page\n"
1739            " - a/A: bookmark the item under cursor or current page\n"
1740            " - B: list all bookmarks\n"
1741            " - s/S: show current history stack or all previously visted pages\n"
1742            " - r: redraw current page (using cached contents if available)\n"
1743            " - R: reload current page (regenerates cache)\n"
1744            " - !: set character coding system for gopher (default is to autodetect)\n"
1745            " - T: toggle TLS gopher mode\n"
1746            " - F: forget/discard current TLS client certificate\n"
1747            " - .: display the raw server response for the current page\n"
1748            "\n"
1749            "Start your exploration of gopher space and gemini:\n")
1750    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1751                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1752    (elpher-insert-index-record "Project Gemini home page"
1753                                (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1754    (insert "\n"
1755            "Alternatively, select a search engine and enter some search terms:\n")
1756    (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1757                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1758    (elpher-insert-index-record "Gemini Search Engine (geminispace.info)"
1759                                (elpher-address-from-url "gemini://geminispace.info/search"))
1760    (insert "\n"
1761            "Your bookmarks are stored in your ")
1762    (insert-text-button "bookmark list"
1763                        'face 'link
1764                        'action #'elpher-click-link
1765                        'follow-link t
1766                        'help-echo #'elpher--page-button-help
1767                        'elpher-page
1768                        (elpher-make-page "Elpher Bookmarks"
1769                                          (elpher-make-about-address 'bookmarks)))
1770    (insert ".\n")
1771    (insert (propertize
1772             "(Bookmarks from legacy elpher-bookmarks files will be automatically imported.)\n"
1773             'face 'shadow))
1774    (insert "\n"
1775            "The gopher home of the Elpher project is here:\n")
1776    (elpher-insert-index-record "The Elpher Project Page"
1777                                (elpher-make-gopher-address ?1
1778                                                            "/projects/elpher/"
1779                                                            "thelambdalab.xyz"
1780                                                            70))
1781    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1782      (insert "\n"
1783              "The following info documentation is available:\n"
1784              "   - ")
1785      (insert-text-button "Elpher Manual"
1786                          'face 'link
1787                          'action (lambda (_)
1788                                    (interactive)
1789                                    (info "(elpher)"))
1790                          'follow-link t
1791                          'help-echo help-string)
1792      (insert "\n   - ")
1793      (insert-text-button "Changes introduced by the latest release"
1794                        'face 'link
1795                        'action (lambda (_)
1796                                  (interactive)
1797                                  (info "(elpher)News"))
1798                        'follow-link t
1799                        'help-echo help-string))
1800    (insert "\n")
1801    (insert (propertize
1802             (concat "(These documents should be available if you have installed Elpher \n"
1803                     " using MELPA. Otherwise you may have to install the manual yourself.)\n")
1804             'face 'shadow))
1805    (elpher-restore-pos)))
1806
1807 ;; History page retrieval
1808
1809 (defun elpher-show-history ()
1810   "Show the current contents of elpher's history stack.
1811 Use \\[elpher-show-visited-pages] to see the entire history.
1812 This is rendered using `elpher-get-history-page' via `elpher-type-map'."
1813   (interactive)
1814   (elpher-visit-page
1815    (elpher-make-page "Current History Stack"
1816                      (elpher-make-about-address 'history))))
1817
1818 (defun elpher-show-visited-pages ()
1819   "Show the all the pages you've visited using Elpher.
1820 Use \\[elpher-show-history] to see just the current history stack.
1821 This is rendered using `elpher-get-visited-pages-page' via `elpher-type-map'."
1822   (interactive)
1823   (elpher-visit-page
1824    (elpher-make-page "Elpher Visted Pages"
1825                      (elpher-make-about-address 'visited-pages))))
1826
1827 (defun elpher-get-history-page (renderer)
1828   "Getter which displays the history page (RENDERER must be nil)."
1829   (when renderer
1830     (elpher-visit-previous-page)
1831     (error "Command not supported for history page"))
1832   (elpher-display-history-links elpher-history "Current history stack"))
1833
1834 (defun elpher-get-visited-pages-page (renderer)
1835   "Getter which displays the list of visited pages (RENDERER must be nil)."
1836   (when renderer
1837     (elpher-visit-previous-page)
1838     (error "Command not supported for history page"))
1839   (elpher-display-history-links
1840    (seq-filter (lambda (page)
1841                  (not (elpher-address-about-p (elpher-page-address page))))
1842                elpher-visited-pages)
1843    "All visited pages"))
1844
1845 (defun elpher-display-history-links (pages title)
1846   "Show all PAGES in an Elpher buffer with a given TITLE."
1847   (let* ((title-line (concat " ---- " title " ----"))
1848          (footer-line (make-string (length title-line) ?-)))
1849     (elpher-with-clean-buffer
1850      (insert title-line "\n\n")
1851      (if pages
1852          (dolist (page pages)
1853            (when page
1854              (let ((display-string (elpher-page-display-string page))
1855                    (address (elpher-page-address page)))
1856                (elpher-insert-index-record display-string address))))
1857        (insert "No history items found.\n"))
1858      (insert "\n " footer-line "\n"
1859              "Select an entry or press 'u' to return to the previous page.")
1860      (elpher-restore-pos))))
1861
1862
1863 ;;; Bookmarks
1864
1865 ;; This code allows Elpher to use the standard Emacs bookmarks: `C-x r
1866 ;; m' to add a bookmark, `C-x r l' to list bookmarks (which is where
1867 ;; you can anotate bookmarks!), `C-x r b' to jump to a bookmark, and
1868 ;; so on. See the Bookmarks section in the Emacs info manual for more.
1869
1870 (defvar elpher-bookmark-link nil
1871   "Prefer bookmarking a link or the current page.
1872 Bind this variable dynamically, or set it to t.
1873 If you set it to t, the commands \\[bookmark-set-no-overwrite]
1874 and \\[elpher-set-bookmark-no-overwrite] do the same thing.")
1875
1876 (defun elpher-bookmark-make-record ()
1877   "Return a bookmark record.
1878 If `elpher-bookmark-link' is non-nil and point is on a link button,
1879 return a bookmark record for that link.  Otherwise, return a bookmark
1880 record for the current elpher page."
1881   (let* ((button (and elpher-bookmark-link (button-at (point))))
1882          (page (if button
1883                    (button-get button 'elpher-page)
1884                  elpher-current-page)))
1885     (unless page
1886       (error "Cannot bookmark this link"))
1887     (let* ((address (elpher-page-address page))
1888            (url (elpher-address-to-url address))
1889            (display-string (elpher-page-display-string page))
1890            (pos (if button nil (point))))
1891       (if (elpher-address-about-p address)
1892           (error "Cannot bookmark %s" display-string)
1893         `(,display-string
1894           (defaults . (,display-string))
1895           (position . ,pos)
1896           (location . ,url)
1897           (handler . elpher-bookmark-jump))))))
1898
1899 ;;;###autoload
1900 (defun elpher-bookmark-jump (bookmark)
1901   "Handler used to open a bookmark using elpher.
1902 The argument BOOKMARK is a bookmark record passed to the function.
1903 This handler is responsible for loading the bookmark in some buffer,
1904 then making that buffer the current buffer.  It should not switch
1905 to the buffer."
1906   (let* ((url (cdr (assq 'location bookmark)))
1907          (cleaned-url (string-trim url))
1908          (page (elpher-page-from-url cleaned-url))
1909          (buffer (get-buffer-create elpher-buffer-name)))
1910     (elpher-with-clean-buffer
1911      (elpher-visit-page page))
1912     (set-buffer buffer)
1913     nil))
1914
1915 (defun elpher-bookmark-link ()
1916   "Bookmark the link at point.
1917 To bookmark the current page, use \\[elpher-bookmark-current]."
1918   (interactive)
1919   (let ((elpher-bookmark-link t))
1920     (bookmark-set-no-overwrite)))
1921
1922 (defun elpher-bookmark-current ()
1923   "Bookmark the current page.
1924 To bookmark the link at point use \\[elpher-bookmark-link]."
1925   (interactive)
1926   (call-interactively #'bookmark-set-no-overwrite))
1927
1928 (defun elpher-bookmark-import (file)
1929   "Import legacy Elpher bookmarks file FILE into Emacs bookmarks."
1930   (interactive (list (if (and (boundp 'elpher-bookmarks-file)
1931                               (file-readable-p elpher-bookmarks-file))
1932                          elpher-bookmarks-file
1933                        (read-file-name "Old Elpher bookmarks: "
1934                                        user-emacs-directory nil t
1935                                        "elpher-bookmarks"))))
1936   (dolist (bookmark (with-temp-buffer
1937                       (insert-file-contents file)
1938                       (read (current-buffer))))
1939     (let* ((display-string (car bookmark))
1940            (url (cadr bookmark))
1941            (record `(,display-string
1942                      (location . ,url)
1943                      (handler . elpher-bookmark-jump))))
1944       (bookmark-store display-string (cdr record) t)))
1945   (bookmark-save))
1946
1947 (defun elpher-get-bookmarks-page (renderer)
1948   "Getter which displays the bookmarks (RENDERER must be nil)."
1949   (when renderer
1950     (elpher-visit-previous-page)
1951     (error "Command not supported for bookmarks page"))
1952
1953   (let ((old-bookmarks-file (or (and (boundp 'elpher-bookmarks-file)
1954                                      elpher-bookmarks-file)
1955                                 (locate-user-emacs-file "elpher-bookmarks"))))
1956     (when (and (file-readable-p old-bookmarks-file)
1957                (y-or-n-p (concat "Legacy elpher-bookmarks file \""
1958                                  old-bookmarks-file
1959                                  "\" found. Import now?")))
1960       (elpher-bookmark-import old-bookmarks-file)
1961       (rename-file old-bookmarks-file (concat old-bookmarks-file "-legacy"))))
1962
1963   (if (and elpher-use-emacs-bookmark-menu
1964            elpher-history)
1965       (progn
1966         (elpher-visit-previous-page)
1967         (call-interactively #'bookmark-bmenu-list))
1968     (elpher-with-clean-buffer
1969      (insert " ---- Elpher Bookmarks ---- \n\n")
1970      (bookmark-maybe-load-default-file)
1971      (dolist (bookmark (bookmark-maybe-sort-alist))
1972        (when (eq #'elpher-bookmark-jump (alist-get 'handler (cdr bookmark)))
1973          (let* ((name (car bookmark))
1974                 (url (alist-get 'location (cdr bookmark)))
1975                 (address (elpher-address-from-url url)))
1976            (elpher-insert-index-record name address))))
1977      (when (<= (line-number-at-pos) 3)
1978        (insert "No bookmarked pages found.\n"))
1979      (insert "\n --------------------------\n\n"
1980              "Select an entry or press 'u' to return to the previous page.\n\n"
1981              "Bookmarks can be renamed or deleted via the ")
1982      (insert-text-button "Emacs bookmark menu"
1983                          'action (lambda (_)
1984                                    (interactive)
1985                                    (call-interactively #'bookmark-bmenu-list))
1986                          'follow-link t
1987                          'help-echo "RET,mouse-1: open Emacs bookmark menu")
1988      (insert (substitute-command-keys
1989               ",\nwhich can also be opened from anywhere using '\\[bookmark-bmenu-list]'."))
1990      (elpher-restore-pos))))
1991
1992 (defun elpher-show-bookmarks ()
1993   "Interactive function to display the current list of elpher bookmarks."
1994   (interactive)
1995   (elpher-visit-page
1996    (elpher-make-page "Elpher Bookmarks"
1997                      (elpher-make-about-address 'bookmarks))))
1998
1999
2000 ;;; Integrations
2001 ;;
2002
2003 ;;; Org
2004
2005 (defun elpher-org-export-link (link description format protocol)
2006   "Export a LINK with DESCRIPTION for the given PROTOCOL and FORMAT.
2007
2008 FORMAT is an Org export backend.  DESCRIPTION may be nil.  PROTOCOL may be one
2009 of gemini, gopher or finger."
2010   (let* ((url (if (equal protocol "elpher")
2011                   (string-remove-prefix "elpher:" link)
2012                 (format "%s:%s" protocol link)))
2013          (desc (or description url)))
2014     (pcase format
2015       (`gemini (format "=> %s %s" url desc))
2016       (`html (format "<a href=\"%s\">%s</a>" url desc))
2017       (`latex (format "\\href{%s}{%s}" url desc))
2018       (_ (if (not description)
2019              url
2020            (format "%s (%s)" desc url))))))
2021
2022 (defun elpher-org-store-link ()
2023   "Store link to an `elpher' page in Org."
2024   (when (eq major-mode 'elpher-mode)
2025     (let* ((url (elpher-info-current))
2026            (desc (car elpher-current-page))
2027            (protocol (cond
2028                       ((string-prefix-p "gemini:" url) "gemini")
2029                       ((string-prefix-p "gopher:" url) "gopher")
2030                       ((string-prefix-p "finger:" url) "finger")
2031                       (t "elpher"))))
2032       (when (equal "elpher" protocol)
2033         ;; Weird link. Or special inner link?
2034         (setq url (concat "elpher:" url)))
2035       (org-link-store-props :type protocol :link url :description desc)
2036       t)))
2037
2038 (defun elpher-org-follow-link (link protocol)
2039   "Visit a LINK for the given PROTOCOL.
2040
2041 PROTOCOL may be one of gemini, gopher or finger.  This method also
2042 supports the old protocol elpher, where the link is self-contained."
2043   (let ((url (if (equal protocol "elpher")
2044                  (string-remove-prefix "elpher:" link)
2045                (format "%s:%s" protocol link))))
2046     (elpher-go url)))
2047
2048 (defun elpher-org-mode-integration ()
2049   "Set up `elpher' integration for `org-mode'."
2050   (org-link-set-parameters
2051    "elpher"
2052    :store #'elpher-org-store-link
2053    :export (lambda (link description format _plist)
2054              (elpher-org-export-link link description format "elpher"))
2055    :follow (lambda (link _arg) (elpher-org-follow-link link "elpher")))
2056   (org-link-set-parameters
2057    "gemini"
2058    :export (lambda (link description format _plist)
2059              (elpher-org-export-link link description format "gemini"))
2060    :follow (lambda (link _arg) (elpher-org-follow-link link "gemini")))
2061   (org-link-set-parameters
2062    "gopher"
2063    :export (lambda (link description format _plist)
2064              (elpher-org-export-link link description format "gopher"))
2065    :follow (lambda (link _arg) (elpher-org-follow-link link "gopher")))
2066   (org-link-set-parameters
2067    "finger"
2068    :export (lambda (link description format _plist)
2069              (elpher-org-export-link link description format "finger"))
2070    :follow (lambda (link _arg) (elpher-org-follow-link link "finger"))))
2071
2072 (add-hook 'org-mode-hook #'elpher-org-mode-integration)
2073
2074 ;;; Browse URL
2075
2076 ;;;###autoload
2077 (defun elpher-browse-url-elpher (url &rest _args)
2078   "Browse URL using Elpher.  This function is used by `browse-url'."
2079   (interactive (browse-url-interactive-arg "Elpher URL: "))
2080   (elpher-go url))
2081
2082 ;; Use elpher to open gopher, finger and gemini links
2083 ;; For recent version of `browse-url' package
2084 (if (boundp 'browse-url-default-handlers)
2085     (add-to-list
2086      'browse-url-default-handlers
2087      '("^\\(gopher\\|finger\\|gemini\\)://" . elpher-browse-url-elpher))
2088   ;; Patch `browse-url-browser-function' for older ones. The value of
2089   ;; that variable is `browse-url-default-browser' by default, so
2090   ;; that's the function that gets advised. If the value is an alist,
2091   ;; however, we don't know what to do. Better not interfere?
2092   (when (and (symbolp browse-url-browser-function)
2093              (fboundp browse-url-browser-function))
2094     (advice-add browse-url-browser-function :before-while
2095                 (lambda (url &rest _args)
2096                   "Handle gemini, gopher, and finger schemes using Elpher."
2097                   (let ((scheme (downcase (car (split-string url ":" t)))))
2098                     (if (member scheme '("gemini" "gopher" "finger"))
2099                         ;; `elpher-go' always returns nil, which will stop the
2100                         ;; advice chain here in a before-while
2101                         (elpher-go url)
2102                       ;; chain must continue, then return t.
2103                       t))))))
2104
2105 ;; Register "gemini://" as a URI scheme so `browse-url' does the right thing
2106 (with-eval-after-load 'thingatpt
2107   (add-to-list 'thing-at-point-uri-schemes "gemini://"))
2108
2109 ;;; Mu4e:
2110
2111 ;; Make mu4e aware of the gemini world
2112 (setq mu4e~view-beginning-of-url-regexp
2113       "\\(?:https?\\|gopher\\|finger\\|gemini\\)://\\|mailto:")
2114
2115 ;;; eww:
2116
2117 ;; Let elpher handle gemini, gopher links in eww buffer.
2118 (setq eww-use-browse-url
2119       "\\`mailto:\\|\\(\\`gemini\\|\\`gopher\\|\\`finger\\)://")
2120
2121
2122 ;;; Interactive procedures
2123 ;;
2124
2125 (defun elpher-next-link ()
2126   "Move point to the next link on the current page."
2127   (interactive)
2128   (forward-button 1))
2129
2130 (defun elpher-prev-link ()
2131   "Move point to the previous link on the current page."
2132   (interactive)
2133   (backward-button 1))
2134
2135 (defun elpher-follow-current-link ()
2136   "Open the link or url at point."
2137   (interactive)
2138   (push-button))
2139
2140 ;;;###autoload
2141 (defun elpher-go (host-or-url)
2142   "Go to a particular gopher site HOST-OR-URL.
2143 When run interactively HOST-OR-URL is read from the minibuffer."
2144   (interactive (list
2145                 (read-string (format "Visit URL (default scheme %s): " (elpher-get-default-url-scheme)))))
2146   (let ((trimmed-host-or-url (string-trim host-or-url)))
2147     (unless (string-empty-p trimmed-host-or-url)
2148       (let ((page (elpher-page-from-url trimmed-host-or-url
2149                                         (elpher-get-default-url-scheme))))
2150         (unless (get-buffer-window elpher-buffer-name t)
2151           (switch-to-buffer elpher-buffer-name))
2152         (elpher-with-clean-buffer
2153          (elpher-visit-page page))
2154         nil)))) ; non-nil value is displayed by eshell
2155
2156 (defun elpher-go-current ()
2157   "Go to a particular site read from the minibuffer, initialized with the current URL."
2158   (interactive)
2159   (let* ((address (elpher-page-address elpher-current-page))
2160          (url (read-string (format "Visit URL (default scheme %s): " (elpher-get-default-url-scheme))
2161                            (elpher-address-to-url address))))
2162     (unless (string-empty-p (string-trim url))
2163       (elpher-visit-page (elpher-page-from-url url)))))
2164
2165 (defun elpher-redraw ()
2166   "Redraw current page."
2167   (interactive)
2168   (elpher-visit-page elpher-current-page))
2169
2170 (defun elpher-reload ()
2171   "Reload current page."
2172   (interactive)
2173   (elpher-reload-current-page))
2174
2175 (defun elpher-toggle-tls ()
2176   "Toggle TLS encryption mode for gopher."
2177   (interactive)
2178   (setq elpher-use-tls (not elpher-use-tls))
2179   (if elpher-use-tls
2180       (if (gnutls-available-p)
2181           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
2182         (setq elpher-use-tls nil)
2183         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
2184     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
2185
2186 (defun elpher-view-raw ()
2187   "View raw server response for current page."
2188   (interactive)
2189   (if (elpher-address-about-p (elpher-page-address elpher-current-page))
2190       (error "This page was not generated by a server")
2191     (elpher-visit-page elpher-current-page
2192                        #'elpher-render-raw)))
2193
2194 (defun elpher-back ()
2195   "Go to previous site."
2196   (interactive)
2197   (elpher-visit-previous-page))
2198
2199 (defun elpher-back-to-start ()
2200   "Go all the way back to the start page."
2201   (interactive)
2202   (setq-local elpher-current-page nil)
2203   (setq-local elpher-history nil)
2204   (elpher-visit-page (elpher-make-start-page)))
2205
2206 (defun elpher-download ()
2207   "Download the link at point."
2208   (interactive)
2209   (let ((button (button-at (point))))
2210     (if button
2211         (let ((page (button-get button 'elpher-page)))
2212           (unless page
2213             (error "Not an elpher page"))
2214           (when (elpher-address-about-p (elpher-page-address page))
2215             (error "Cannot download %s" (elpher-page-display-string page)))
2216           (elpher-visit-page (button-get button 'elpher-page)
2217                              #'elpher-render-download))
2218       (error "No link selected"))))
2219
2220 (defun elpher-download-current ()
2221   "Download the current page."
2222   (interactive)
2223   (if (elpher-address-about-p (elpher-page-address elpher-current-page))
2224       (error "Cannot download %s"
2225              (elpher-page-display-string elpher-current-page))
2226     (elpher-visit-page (elpher-make-page
2227                         (elpher-page-display-string elpher-current-page)
2228                         (elpher-page-address elpher-current-page))
2229                        #'elpher-render-download
2230                        t)))
2231
2232 (defun elpher--build-link-map ()
2233   "Build alist mapping link names to destination pages in current buffer."
2234   (let ((link-map nil)
2235         (b (next-button (point-min) t)))
2236     (while b
2237       (push (cons (button-label b) b) link-map)
2238       (setq b (next-button (button-start b))))
2239     link-map))
2240
2241 (defun elpher-jump ()
2242   "Select a directory entry by name.  Similar to the info browser (m)enu command."
2243   (interactive)
2244   (let* ((link-map (elpher--build-link-map)))
2245     (if link-map
2246         (let ((key (let ((completion-ignore-case t))
2247                      (completing-read "Directory item/link: "
2248                                       link-map nil t))))
2249           (if (and key (> (length key) 0))
2250               (let ((b (cdr (assoc key link-map))))
2251                 (goto-char (button-start b))
2252                 (button-activate b)))))))
2253
2254 (defun elpher-root-dir ()
2255   "Visit root of current server."
2256   (interactive)
2257   (let ((address (elpher-page-address elpher-current-page)))
2258     (if (not (elpher-address-about-p address))
2259         (if (or (member (url-filename address) '("/" ""))
2260                 (and (elpher-address-gopher-p address)
2261                      (= (length (elpher-gopher-address-selector address)) 0)))
2262             (error "Already at root directory of current server")
2263           (let ((address-copy (elpher-address-from-url
2264                                (elpher-address-to-url address))))
2265             (setf (url-filename address-copy) "")
2266             (elpher-go (elpher-address-to-url address-copy))))
2267       (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
2268
2269 (defun elpher-info-page (page)
2270   "Display URL of PAGE in minibuffer."
2271   (let* ((address (elpher-page-address page))
2272          (url (elpher-address-to-url address))
2273          (iri (elpher-address-to-iri address)))
2274     (if (equal url iri)
2275         (message "%s" url)
2276       (message "%s (Raw: %s)" iri url))))
2277
2278 (defun elpher-info-link ()
2279   "Display information on page corresponding to link at point."
2280   (interactive)
2281   (let ((button (button-at (point))))
2282     (unless button
2283       (error "No item selected"))
2284     (let ((page (button-get button 'elpher-page)))
2285       (unless page
2286         (error "Not an elpher page"))
2287       (elpher-info-page page))))
2288
2289 (defun elpher-info-current ()
2290   "Display information on current page."
2291   (interactive)
2292   (elpher-info-page elpher-current-page))
2293
2294 (defun elpher-copy-page-url (page)
2295   "Copy URL representation of address of PAGE to `kill-ring'."
2296   (let* ((address (elpher-page-address page))
2297          (url (elpher-address-to-url address)))
2298     (message "Copied \"%s\" to kill-ring/clipboard." url)
2299     (kill-new url)))
2300
2301 (defun elpher-copy-link-url ()
2302   "Copy URL of item at point to `kill-ring'."
2303   (interactive)
2304   (let ((button (button-at (point))))
2305     (unless button
2306       (error "No item selected"))
2307     (let ((page (button-get button 'elpher-page)))
2308       (unless page
2309         (error "Not an elpher page"))
2310       (elpher-copy-page-url page))))
2311
2312 (defun elpher-copy-current-url ()
2313   "Copy URL of current page to `kill-ring'."
2314   (interactive)
2315   (elpher-copy-page-url elpher-current-page))
2316
2317 (defun elpher-set-gopher-coding-system ()
2318   "Specify an explicit character coding system for gopher selectors."
2319   (interactive)
2320   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
2321     (setq elpher-user-coding-system system)
2322     (if system
2323         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
2324       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
2325
2326
2327 ;;; Mode and keymap
2328 ;;
2329
2330 (defvar elpher-mode-map
2331   (let ((map (make-sparse-keymap)))
2332     (define-key map (kbd "TAB") 'elpher-next-link)
2333     (define-key map (kbd "<backtab>") 'elpher-prev-link)
2334     (define-key map (kbd "C-M-i") 'elpher-prev-link)
2335     (define-key map (kbd "u") 'elpher-back)
2336     (define-key map (kbd "-") 'elpher-back)
2337     (define-key map (kbd "^") 'elpher-back)
2338     (define-key map [mouse-3] 'elpher-back)
2339     (define-key map (kbd "U") 'elpher-back-to-start)
2340     (define-key map (kbd "g") 'elpher-go)
2341     (define-key map (kbd "o") 'elpher-go-current)
2342     (define-key map (kbd "O") 'elpher-root-dir)
2343     (define-key map (kbd "s") 'elpher-show-history)
2344     (define-key map (kbd "S") 'elpher-show-visited-pages)
2345     (define-key map (kbd "r") 'elpher-redraw)
2346     (define-key map (kbd "R") 'elpher-reload)
2347     (define-key map (kbd "T") 'elpher-toggle-tls)
2348     (define-key map (kbd ".") 'elpher-view-raw)
2349     (define-key map (kbd "d") 'elpher-download)
2350     (define-key map (kbd "D") 'elpher-download-current)
2351     (define-key map (kbd "m") 'elpher-jump)
2352     (define-key map (kbd "i") 'elpher-info-link)
2353     (define-key map (kbd "I") 'elpher-info-current)
2354     (define-key map (kbd "c") 'elpher-copy-link-url)
2355     (define-key map (kbd "C") 'elpher-copy-current-url)
2356     (define-key map (kbd "a") 'elpher-bookmark-link)
2357     (define-key map (kbd "A") 'elpher-bookmark-current)
2358     (define-key map (kbd "B") 'elpher-show-bookmarks)
2359     (define-key map (kbd "!") 'elpher-set-gopher-coding-system)
2360     (define-key map (kbd "F") 'elpher-forget-current-certificate)
2361     (when (fboundp 'evil-define-key*)
2362       (evil-define-key*
2363        'motion map
2364        (kbd "TAB") 'elpher-next-link
2365        (kbd "C-") 'elpher-follow-current-link
2366        (kbd "C-t") 'elpher-back
2367        (kbd "u") 'elpher-back
2368        (kbd "-") 'elpher-back
2369        (kbd "^") 'elpher-back
2370        [mouse-3] 'elpher-back
2371        (kbd "U") 'elpher-back-to-start
2372        (kbd "g") 'elpher-go
2373        (kbd "o") 'elpher-go-current
2374        (kbd "O") 'elpher-root-dir
2375        (kbd "s") 'elpher-show-history
2376        (kbd "S") 'elpher-show-visited-pages
2377        (kbd "r") 'elpher-redraw
2378        (kbd "R") 'elpher-reload
2379        (kbd "T") 'elpher-toggle-tls
2380        (kbd ".") 'elpher-view-raw
2381        (kbd "d") 'elpher-download
2382        (kbd "D") 'elpher-download-current
2383        (kbd "m") 'elpher-jump
2384        (kbd "i") 'elpher-info-link
2385        (kbd "I") 'elpher-info-current
2386        (kbd "c") 'elpher-copy-link-url
2387        (kbd "C") 'elpher-copy-current-url
2388        (kbd "a") 'elpher-bookmark-link
2389        (kbd "A") 'elpher-bookmark-current
2390        (kbd "B") 'elpher-show-bookmarks
2391        (kbd "!") 'elpher-set-gopher-coding-system
2392        (kbd "F") 'elpher-forget-current-certificate))
2393     map)
2394   "Keymap for gopher client.")
2395
2396 (define-derived-mode elpher-mode special-mode "elpher"
2397   "Major mode for elpher, an elisp gopher client.
2398
2399 This mode is automatically enabled by the interactive
2400 functions which initialize the client, namely
2401 `elpher', and `elpher-go'."
2402   (setq-local elpher-current-page nil)
2403   (setq-local elpher-history nil)
2404   (setq-local elpher-buffer-name (buffer-name))
2405   (setq-local bookmark-make-record-function #'elpher-bookmark-make-record)
2406   (setq-local imenu-create-index-function #'elpher-build-current-imenu-index))
2407
2408 (when (fboundp 'evil-set-initial-state)
2409   (evil-set-initial-state 'elpher-mode 'motion))
2410
2411
2412 ;;; Main start procedure
2413 ;;
2414
2415 ;;;###autoload
2416 (defun elpher (&optional arg)
2417   "Start elpher with default landing page.
2418 The buffer used for Elpher sessions is determined by the value of
2419 ‘elpher-buffer-name’.  If there is already an Elpher session active in
2420 that buffer, Emacs will simply switch to it.  Otherwise, a new session
2421 will begin.  A numeric prefix ARG (as in ‘\\[universal-argument] 42
2422 \\[execute-extended-command] elpher RET’) switches to the session with
2423 that number, creating it if necessary.  A non numeric prefix ARG means
2424 to create a new session.  Returns the buffer selected (or created)."
2425   (interactive "P")
2426   (let* ((name (default-value 'elpher-buffer-name))
2427          (buf (cond ((numberp arg)
2428                      (get-buffer-create (format "%s<%d>" name arg)))
2429                     (arg
2430                      (generate-new-buffer name))
2431                     (t
2432                      (get-buffer-create name)))))
2433     (pop-to-buffer-same-window buf)
2434     (unless (buffer-modified-p)
2435       (elpher-mode)
2436       (elpher-visit-page (elpher-make-start-page))
2437       "Started Elpher."))); Otherwise (elpher) evaluates to start page string.
2438
2439 ;;; elpher.el ends here