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