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