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