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