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