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