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