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