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