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