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