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