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