Work around Doom emacs tls problems.
[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              (gnutls-verify-error nil) ; We use the NSM for verification
551              (port (elpher-address-port address))
552              (host (elpher-address-host address))
553              (selector-string-parts nil)
554              (bytes-received 0)
555              (hkbytes-received 0)
556              (proc (open-network-stream "elpher-process"
557                                         nil
558                                         (if force-ipv4 (dns-query host) host)
559                                         (if (> port 0) port 70)
560                                         :type (if elpher-use-tls 'tls 'plain)
561                                         :nowait t))
562              (timer (run-at-time elpher-connection-timeout
563                                  nil
564                                  (lambda ()
565                                    (pcase (process-status proc)
566                                      ('failed
567                                       (if (and (not (equal (elpher-address-protocol address)
568                                                            "gophers"))
569                                                elpher-use-tls
570                                                (or elpher-auto-disengage-TLS
571                                                    (yes-or-no-p "Could not establish encrypted connection.  Disable TLS mode?")))
572                                           (progn
573                                             (message "Disabling TLS mode.")
574                                             (setq elpher-use-tls nil)
575                                             (elpher-get-selector address renderer))
576                                         (elpher-network-error address "Could not establish encrypted connection")))
577                                      ('connect
578                                       (elpher-process-cleanup)
579                                       (unless force-ipv4
580                                         (message "Connection timed out. Retrying with IPv4 address.")
581                                         (elpher-get-selector address renderer t))))))))
582         (setq elpher-network-timer timer)
583         (set-process-coding-system proc 'binary)
584         (set-process-filter proc
585                             (lambda (_proc string)
586                               (when timer
587                                 (cancel-timer timer)
588                                 (setq timer nil))
589                               (setq bytes-received (+ bytes-received (length string)))
590                               (let ((new-hkbytes-received (/ bytes-received 102400)))
591                                 (when (> new-hkbytes-received hkbytes-received)
592                                   (setq hkbytes-received new-hkbytes-received)
593                                   (with-current-buffer "*elpher*"
594                                     (let ((inhibit-read-only t))
595                                       (goto-char (point-min))
596                                       (beginning-of-line 2)
597                                       (delete-region (point) (point-max))
598                                       (insert "("
599                                               (number-to-string (/ hkbytes-received 10.0))
600                                               " MB read)")))))
601                               (setq selector-string-parts
602                                     (cons string selector-string-parts))))
603         (set-process-sentinel proc
604                               (lambda (_proc event)
605                                 (condition-case the-error
606                                     (cond
607                                      ((string-prefix-p "deleted" event))
608                                      ((string-prefix-p "open" event)
609                                       (let ((inhibit-eol-conversion t))
610                                         (process-send-string
611                                          proc
612                                          (concat (elpher-gopher-address-selector address)
613                                                  "\r\n"))))
614                                      (t
615                                       (when timer
616                                         (cancel-timer timer)
617                                         (setq timer nil))
618                                       (funcall renderer (apply #'concat
619                                                                (reverse selector-string-parts)))
620                                       (elpher-restore-pos)))
621                                   (error
622                                    (elpher-network-error address the-error))))))
623     (error
624      (error "Error initiating connection to server"))))
625
626 (defun elpher-get-gopher-page (renderer)
627   "Getter function for gopher pages.
628 The RENDERER procedure is used to display the contents of the page
629 once they are retrieved from the gopher server."
630   (let* ((address (elpher-page-address elpher-current-page))
631          (content (elpher-get-cached-content address)))
632     (if (and content (funcall renderer nil))
633         (elpher-with-clean-buffer
634          (insert content)
635          (elpher-restore-pos))
636       (elpher-with-clean-buffer
637        (insert "LOADING... (use 'u' to cancel)\n"))
638       (condition-case the-error
639           (elpher-get-selector address renderer)
640         (error
641          (elpher-network-error address the-error))))))
642
643 ;; Index rendering
644
645 (defun elpher-insert-index (string)
646   "Insert the index corresponding to STRING into the current buffer."
647   ;; Should be able to split directly on CRLF, but some non-conformant
648   ;; LF-only servers sadly exist, hence the following.
649   (let ((str-processed (elpher-preprocess-text-response string)))
650     (dolist (line (split-string str-processed "\n"))
651       (ignore-errors
652         (unless (= (length line) 0)
653           (let* ((type (elt line 0))
654                  (fields (split-string (substring line 1) "\t"))
655                  (display-string (elt fields 0))
656                  (selector (elt fields 1))
657                  (host (elt fields 2))
658                  (port (if (elt fields 3)
659                            (string-to-number (elt fields 3))
660                          nil))
661                  (address (elpher-make-gopher-address type selector host port)))
662             (elpher-insert-index-record display-string address)))))))
663
664 (defun elpher-insert-margin (&optional type-name)
665   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
666   (if type-name
667       (progn
668         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
669                         (concat
670                          (propertize "[" 'face 'elpher-margin-brackets)
671                          (propertize type-name 'face 'elpher-margin-key)
672                          (propertize "]" 'face 'elpher-margin-brackets))))
673         (insert " "))
674     (insert (make-string elpher-margin-width ?\s))))
675
676 (defun elpher-page-button-help (page)
677   "Return a string containing the help text for a button corresponding to PAGE."
678   (let ((address (elpher-page-address page)))
679     (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
680                                           address
681                                         (elpher-address-to-url address)))))
682
683 (defun elpher-insert-index-record (display-string &optional address)
684   "Function to insert an index record into the current buffer.
685 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
686 If ADDRESS is not supplied or nil the record is rendered as an
687 'information' line."
688   (let* ((type (if address (elpher-address-type address) nil))
689          (type-map-entry (cdr (assoc type elpher-type-map))))
690     (if type-map-entry
691         (let* ((margin-code (elt type-map-entry 2))
692                (face (elt type-map-entry 3))
693                (filtered-display-string (ansi-color-filter-apply display-string))
694                (page (elpher-make-page filtered-display-string address)))
695           (elpher-insert-margin margin-code)
696           (insert-text-button filtered-display-string
697                               'face face
698                               'elpher-page page
699                               'action #'elpher-click-link
700                               'follow-link t
701                               'help-echo (elpher-page-button-help page)))
702       (pcase type
703         ('nil ;; Information
704          (elpher-insert-margin)
705          (let ((propertized-display-string
706                 (propertize display-string 'face 'elpher-info)))
707            (insert (elpher-process-text-for-display propertized-display-string))))
708         (`(gopher ,selector-type) ;; Unknown
709          (elpher-insert-margin (concat (char-to-string selector-type) "?"))
710          (insert (propertize display-string
711                              'face 'elpher-unknown)))))
712     (insert "\n")))
713
714 (defun elpher-click-link (button)
715   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
716   (let ((page (button-get button 'elpher-page)))
717     (elpher-visit-page page)))
718
719 (defun elpher-render-index (data &optional _mime-type-string)
720   "Render DATA as an index.  MIME-TYPE-STRING is unused."
721   (elpher-with-clean-buffer
722    (if (not data)
723        t
724      (elpher-insert-index data)
725      (elpher-cache-content (elpher-page-address elpher-current-page)
726                            (buffer-string)))))
727
728 ;; Text rendering
729
730 (defconst elpher-url-regex
731   "\\([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\-_~?/@|#]\\)?\\)?"
732   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
733
734 (defun elpher-buttonify-urls (string)
735   "Turn substrings which look like urls in STRING into clickable buttons."
736   (with-temp-buffer
737     (insert string)
738     (goto-char (point-min))
739     (while (re-search-forward elpher-url-regex nil t)
740       (let ((page (elpher-make-page (substring-no-properties (match-string 0))
741                                     (elpher-address-from-url (match-string 0)))))
742           (make-text-button (match-beginning 0)
743                             (match-end 0)
744                             'elpher-page  page
745                             'action #'elpher-click-link
746                             'follow-link t
747                             'help-echo (elpher-page-button-help page)
748                             'face 'button)))
749     (buffer-string)))
750
751 (defconst elpher-ansi-regex "\x1b\\[[^m]*m"
752   "Wildly incomplete regexp used to strip out some troublesome ANSI escape sequences.")
753
754 (defun elpher-process-text-for-display (string)
755   "Perform any desired processing of STRING prior to display as text.
756 Currently includes buttonifying URLs and processing ANSI escape codes."
757   (elpher-buttonify-urls (if elpher-filter-ansi-from-text
758                              (ansi-color-filter-apply string)
759                            (ansi-color-apply string))))
760
761 (defun elpher-render-text (data &optional _mime-type-string)
762   "Render DATA as text.  MIME-TYPE-STRING is unused."
763   (elpher-with-clean-buffer
764    (if (not data)
765        t
766      (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
767      (elpher-cache-content
768       (elpher-page-address elpher-current-page)
769       (buffer-string)))))
770
771 ;; Image retrieval
772
773 (defun elpher-render-image (data &optional _mime-type-string)
774   "Display DATA as image.  MIME-TYPE-STRING is unused."
775   (if (not data)
776       nil
777     (if (display-images-p)
778         (progn
779           (let ((image (create-image
780                         data
781                         nil t)))
782             (elpher-with-clean-buffer
783              (insert-image image)
784              (elpher-restore-pos))))
785       (elpher-render-download data))))
786
787 ;; Search retrieval and rendering
788
789 (defun elpher-get-gopher-query-page (renderer)
790   "Getter for gopher addresses requiring input.
791 The response is rendered using the rendering function RENDERER."
792    (let* ((address (elpher-page-address elpher-current-page))
793           (content (elpher-get-cached-content address))
794           (aborted t))
795     (if (and content (funcall renderer nil))
796         (elpher-with-clean-buffer
797          (insert content)
798          (elpher-restore-pos)
799          (message "Displaying cached search results.  Reload to perform a new search."))
800       (unwind-protect
801           (let* ((query-string (read-string "Query: "))
802                  (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
803                  (search-address (elpher-make-gopher-address ?1
804                                                              query-selector
805                                                              (elpher-address-host address)
806                                                              (elpher-address-port address)
807                                                              (equal (elpher-address-type address) "gophers"))))
808             (setq aborted nil)
809
810             (elpher-with-clean-buffer
811              (insert "LOADING RESULTS... (use 'u' to cancel)"))
812             (elpher-get-selector search-address renderer))
813         (if aborted
814             (elpher-visit-previous-page))))))
815  
816 ;; Raw server response rendering
817
818 (defun elpher-render-raw (data &optional mime-type-string)
819   "Display raw DATA in buffer.  MIME-TYPE-STRING is also displayed if provided."
820   (if (not data)
821       nil
822     (elpher-with-clean-buffer
823      (when mime-type-string
824        (insert "MIME type specified by server: '" mime-type-string "'\n"))
825      (insert data)
826      (goto-char (point-min)))
827     (message "Displaying raw server response.  Reload or redraw to return to standard view.")))
828
829 ;; File save "rendering"
830
831 (defun elpher-render-download (data &optional _mime-type-string)
832   "Save DATA to file.  MIME-TYPE-STRING is unused."
833   (if (not data)
834       nil
835     (let* ((address (elpher-page-address elpher-current-page))
836            (selector (if (elpher-address-gopher-p address)
837                          (elpher-gopher-address-selector address)
838                        (elpher-address-filename address))))
839       (elpher-visit-previous-page) ; Do first in case of non-local exits.
840       (let* ((filename-proposal (file-name-nondirectory selector))
841              (filename (read-file-name "Download complete. Save file as: "
842                                        nil nil nil
843                                        (if (> (length filename-proposal) 0)
844                                            filename-proposal
845                                          "download.file"))))
846         (let ((coding-system-for-write 'binary))
847           (with-temp-file filename
848             (insert data)))
849         (message (format "Saved to file %s." filename))))))
850
851 ;; HTML rendering
852
853 (defun elpher-render-html (data &optional _mime-type-string)
854   "Render DATA as HTML using shr.  MIME-TYPE-STRING is unused."
855   (elpher-with-clean-buffer
856    (if (not data)
857        t
858      (let ((dom (with-temp-buffer
859                   (insert data)
860                   (libxml-parse-html-region (point-min) (point-max)))))
861        (shr-insert-document dom)))))
862
863 ;; Gemini page retrieval
864
865 (defvar elpher-gemini-redirect-chain)
866
867 (defun elpher-get-gemini-response (address renderer &optional force-ipv4)
868   "Retrieve gemini ADDRESS, then render using RENDERER.
869 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
870 to ADDRESS."
871   (unless elpher-gemini-TLS-cert-checks
872     (setq-local network-security-level 'low))
873   (if (not (gnutls-available-p))
874       (error "Cannot establish gemini connection: GnuTLS not available")
875     (unless (< (elpher-address-port address) 65536)
876       (error "Cannot establish gemini connection: port number > 65536"))
877     (condition-case nil
878         (let* ((kill-buffer-query-functions nil)
879                (gnutls-verify-error nil) ; We use the NSM for verification
880                (port (elpher-address-port address))
881                (host (elpher-address-host address))
882                (response-string-parts nil)
883                (bytes-received 0)
884                (hkbytes-received 0)
885                (proc (open-network-stream "elpher-process"
886                                           nil
887                                           (if force-ipv4 (dns-query host) host)
888                                           (if (> port 0) port 1965)
889                                           :type 'tls
890                                           :nowait t))
891                (timer (run-at-time elpher-connection-timeout nil
892                                    (lambda ()
893                                      (elpher-process-cleanup)
894                                      (unless force-ipv4
895                                         ; Try again with IPv4
896                                        (message "Connection timed out.  Retrying with IPv4.")
897                                        (elpher-get-gemini-response address renderer t))))))
898           (setq elpher-network-timer timer)
899           (set-process-coding-system proc 'binary)
900           (set-process-filter proc
901                               (lambda (_proc string)
902                                 (when timer
903                                   (cancel-timer timer)
904                                   (setq timer nil))
905                                 (setq bytes-received (+ bytes-received (length string)))
906                                 (let ((new-hkbytes-received (/ bytes-received 102400)))
907                                   (when (> new-hkbytes-received hkbytes-received)
908                                     (setq hkbytes-received new-hkbytes-received)
909                                     (with-current-buffer "*elpher*"
910                                       (let ((inhibit-read-only t))
911                                         (goto-char (point-min))
912                                         (beginning-of-line 2)
913                                         (delete-region (point) (point-max))
914                                         (insert "("
915                                                 (number-to-string (/ hkbytes-received 10.0))
916                                                 " MB read)")))))
917                                 (setq response-string-parts
918                                       (cons string response-string-parts))))
919           (set-process-sentinel proc
920                                 (lambda (proc event)
921                                   (condition-case the-error
922                                       (cond
923                                        ((string-prefix-p "open" event)    ; request URL
924                                         (let ((inhibit-eol-conversion t))
925                                           (process-send-string
926                                            proc
927                                            (concat (elpher-address-to-url address)
928                                                    "\r\n"))))
929                                        ((string-prefix-p "deleted" event)) ; do nothing
930                                        ((and (not response-string-parts)
931                                              (not force-ipv4))
932                                         ; Try again with IPv4
933                                         (message "Connection failed. Retrying with IPv4.")
934                                         (cancel-timer timer)
935                                         (elpher-get-gemini-response address renderer t))
936                                        (t
937                                         (funcall #'elpher-process-gemini-response
938                                                  (apply #'concat (reverse response-string-parts))
939                                                  renderer)
940                                         (elpher-restore-pos)))
941                                     (error
942                                      (elpher-network-error address the-error))))))
943       (error
944        (error "Error initiating connection to server")))))
945
946 (defun elpher-parse-gemini-response (response)
947   "Parse the RESPONSE string and return a list of components.
948 The list is of the form (code meta body).  A response of nil implies
949 that the response was malformed."
950   (let ((header-end-idx (string-match "\r\n" response)))
951     (if header-end-idx
952         (let ((header (string-trim (substring response 0 header-end-idx)))
953               (body (substring response (+ header-end-idx 2))))
954           (if (>= (length header) 2)
955               (let ((code (substring header 0 2))
956                     (meta (string-trim (substring header 2))))
957                 (list code meta body))
958             (error "Malformed response: No response status found in header %s" header)))
959       (error "Malformed response: No CRLF-delimited header found in response %s" response))))
960
961 (defun elpher-process-gemini-response (response-string renderer)
962   "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
963   (let ((response-components (elpher-parse-gemini-response response-string)))
964     (let ((response-code (elt response-components 0))
965           (response-meta (elt response-components 1))
966           (response-body (elt response-components 2)))
967       (pcase (elt response-code 0)
968         (?1 ; Input required
969          (elpher-with-clean-buffer
970           (insert "Gemini server is requesting input."))
971          (let* ((query-string (read-string (concat response-meta ": ")))
972                 (url (elpher-address-to-url (elpher-page-address elpher-current-page)))
973                 (query-address (elpher-address-from-url (concat url "?" query-string))))
974            (elpher-get-gemini-response query-address renderer)))
975         (?2 ; Normal response
976          (funcall renderer response-body response-meta))
977         (?3 ; Redirect
978          (message "Following redirect to %s" response-meta)
979          (if (>= (length elpher-gemini-redirect-chain) 5)
980              (error "More than 5 consecutive redirects followed"))
981          (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
982            (if (member redirect-address elpher-gemini-redirect-chain)
983                (error "Redirect loop detected"))
984            (if (not (string= (elpher-address-protocol redirect-address)
985                              "gemini"))
986                (error "Server tried to automatically redirect to non-gemini URL: %s"
987                       response-meta))
988            (elpher-page-set-address elpher-current-page redirect-address)
989            (add-to-list 'elpher-gemini-redirect-chain redirect-address)
990            (elpher-get-gemini-response redirect-address renderer)))
991         (?4 ; Temporary failure
992          (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
993                 response-code response-meta))
994         (?5 ; Permanent failure
995          (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
996                 response-code response-meta))
997         (?6 ; Client certificate required
998          (error "Gemini server requires client certificate (unsupported at this time)"))
999         (_other
1000          (error "Gemini server response unknown: %s %s"
1001                 response-code response-meta))))))
1002
1003 (defun elpher-get-gemini-page (renderer)
1004   "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1005   (let* ((address (elpher-page-address elpher-current-page))
1006          (content (elpher-get-cached-content address)))
1007     (condition-case the-error
1008         (if (and content (funcall renderer nil))
1009             (elpher-with-clean-buffer
1010               (insert content)
1011               (elpher-restore-pos))
1012           (elpher-with-clean-buffer
1013            (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1014           (setq elpher-gemini-redirect-chain nil)
1015           (elpher-get-gemini-response address renderer))
1016       (error
1017        (elpher-network-error address the-error)))))
1018
1019
1020 (defun elpher-render-gemini (body &optional mime-type-string)
1021   "Render gemini response BODY with rendering MIME-TYPE-STRING."
1022   (if (not body)
1023       t
1024     (let* ((mime-type-string* (if (or (not mime-type-string)
1025                                       (string-empty-p mime-type-string))
1026                                   "text/gemini; charset=utf-8"
1027                                 mime-type-string))
1028            (mime-type-split (split-string mime-type-string* ";" t))
1029            (mime-type (string-trim (car mime-type-split)))
1030            (parameters (mapcar (lambda (s)
1031                                  (let ((key-val (split-string s "=")))
1032                                    (list (downcase (string-trim (car key-val)))
1033                                          (downcase (string-trim (cadr key-val))))))
1034                                (cdr mime-type-split))))
1035       (when (string-prefix-p "text/" mime-type)
1036         (setq body (decode-coding-string
1037                     body
1038                     (if (assoc "charset" parameters)
1039                         (intern (cadr (assoc "charset" parameters)))
1040                       'utf-8)))
1041         (setq body (replace-regexp-in-string "\r" "" body)))
1042       (pcase mime-type
1043         ((or "text/gemini" "")
1044          (elpher-render-gemini-map body parameters))
1045         ("text/html"
1046          (elpher-render-html body))
1047         ((pred (string-prefix-p "text/"))
1048          (elpher-render-gemini-plain-text body parameters))
1049         ((pred (string-prefix-p "image/"))
1050          (elpher-render-image body))
1051         (_other
1052          (elpher-render-download body))))))
1053
1054 (defun elpher-gemini-get-link-url (link-line)
1055   "Extract the url portion of LINK-LINE, a gemini map file link line.
1056 Returns nil in the event that the contents of the line following the
1057 => prefix are empty."
1058   (let ((l (split-string (substring link-line 2))))
1059     (if l
1060         (string-trim (elt l 0))
1061       nil)))
1062
1063 (defun elpher-gemini-get-link-display-string (link-line)
1064   "Extract the display string portion of LINK-LINE, a gemini map file link line.
1065 Returns the url portion in the event that the display-string portion is empty."
1066   (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1067          (idx (string-match "[ \t]" rest)))
1068     (string-trim (if idx
1069                      (substring rest (+ idx 1))
1070                    rest))))
1071
1072 (defun elpher-collapse-dot-sequences (filename)
1073   "Collapse dot sequences in FILENAME.
1074 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1075   (let* ((path (split-string filename "/"))
1076          (path-reversed-normalized
1077           (seq-reduce (lambda (a b)
1078                         (cond ((and a (equal b "..") (cdr a)))
1079                               ((and (not a) (equal b "..")) a) ;leading .. are dropped
1080                               ((equal b ".") a)
1081                               (t (cons b a))))
1082                       path nil)))
1083     (string-join (reverse path-reversed-normalized) "/")))
1084
1085 (defun elpher-address-from-gemini-url (url)
1086   "Extract address from URL with defaults as per gemini map files."
1087   (let ((address (url-generic-parse-url url)))
1088     (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1089       (setf (url-fullness address) t)
1090       (if (url-host address) ;if there is an explicit host, filenames are absolute
1091           (if (string-empty-p (url-filename address))
1092               (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1093         (setf (url-host address) (url-host (elpher-page-address elpher-current-page)))
1094         (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1095           (setf (url-filename address)
1096                 (concat (file-name-directory
1097                          (url-filename (elpher-page-address elpher-current-page)))
1098                         (url-filename address)))))
1099       (unless (url-type address)
1100         (setf (url-type address) "gemini"))
1101       (if (equal (url-type address) "gemini")
1102           (setf (url-filename address)
1103                 (elpher-collapse-dot-sequences (url-filename address)))))
1104     address))
1105
1106 (defun elpher-gemini-insert-link (link-line)
1107   "Insert link described by LINK-LINE into a text/gemini document."
1108   (let* ((url (elpher-gemini-get-link-url link-line))
1109          (display-string (elpher-gemini-get-link-display-string link-line))
1110          (address (elpher-address-from-gemini-url url))
1111          (type (if address (elpher-address-type address) nil))
1112          (type-map-entry (cdr (assoc type elpher-type-map))))
1113     (when display-string
1114       (insert "→ ")
1115       (if type-map-entry
1116           (let* ((face (elt type-map-entry 3))
1117                  (filtered-display-string (ansi-color-filter-apply display-string))
1118                  (page (elpher-make-page filtered-display-string address)))
1119             (insert-text-button filtered-display-string
1120                                 'face face
1121                                 'elpher-page page
1122                                 'action #'elpher-click-link
1123                                 'follow-link t
1124                                 'help-echo (elpher-page-button-help page)))
1125         (insert (propertize display-string 'face 'elpher-unknown)))
1126       (insert "\n"))))
1127   
1128 (defun elpher-gemini-insert-header (header-line)
1129   "Insert header described by HEADER-LINE into a text/gemini document.
1130 The gemini map file line describing the header is given
1131 by HEADER-LINE."
1132   (when (string-match "^\\(#+\\)[ \t]*" header-line)
1133     (let ((level (length (match-string 1 header-line)))
1134           (header (substring header-line (match-end 0))))
1135       (unless (display-graphic-p)
1136         (insert (make-string level ?#) " "))
1137       (insert (propertize header 'face
1138                           (pcase level
1139                             (1 'elpher-gemini-heading1)
1140                             (2 'elpher-gemini-heading2)
1141                             (3 'elpher-gemini-heading3)
1142                             (_ 'default)))
1143               "\n"))))
1144
1145 (defun elpher-render-gemini-map (data _parameters)
1146   "Render DATA as a gemini map file, PARAMETERS is currently unused."
1147   (elpher-with-clean-buffer
1148    (let ((preformatted nil))
1149      (auto-fill-mode 1)
1150      (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1151      (dolist (line (split-string data "\n"))
1152        (cond
1153         ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1154         (preformatted (insert (elpher-process-text-for-display line) "\n"))
1155         ((string-prefix-p "=>" line) (elpher-gemini-insert-link line))
1156         ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1157         (t (insert (elpher-process-text-for-display line)) (newline)))))
1158    (elpher-cache-content
1159     (elpher-page-address elpher-current-page)
1160     (buffer-string))))
1161
1162 (defun elpher-render-gemini-plain-text (data _parameters)
1163   "Render DATA as plain text file.  PARAMETERS is currently unused."
1164   (elpher-with-clean-buffer
1165    (insert (elpher-process-text-for-display data))
1166    (elpher-cache-content
1167     (elpher-page-address elpher-current-page)
1168     (buffer-string))))
1169
1170 ;; Finger page connection
1171
1172 (defun elpher-get-finger-page (renderer &optional force-ipv4)
1173   "Opens a finger connection to the current page address and renders it using RENDERER."
1174   (let* ((address (elpher-page-address elpher-current-page))
1175          (content (elpher-get-cached-content address)))
1176     (if (and content (funcall renderer nil))
1177         (elpher-with-clean-buffer
1178          (insert content)
1179          (elpher-restore-pos))
1180       (elpher-with-clean-buffer
1181        (insert "LOADING... (use 'u' to cancel)\n"))
1182       (condition-case the-error
1183           (let* ((kill-buffer-query-functions nil)
1184                  (user (let ((filename (elpher-address-filename address)))
1185                          (if (> (length filename) 1)
1186                              (substring filename 1)
1187                            (elpher-address-user address))))
1188                  (port (let ((given-port (elpher-address-port address)))
1189                          (if (> given-port 0) given-port 79)))
1190                  (host (elpher-address-host address))
1191                  (selector-string-parts nil)
1192                  (proc (open-network-stream "elpher-process"
1193                                             nil
1194                                             (if force-ipv4 (dns-query host) host)
1195                                             port
1196                                             :type 'plain
1197                                             :nowait t))
1198                  (timer (run-at-time elpher-connection-timeout
1199                                      nil
1200                                      (lambda ()
1201                                        (pcase (process-status proc)
1202                                          ('connect
1203                                           (elpher-process-cleanup)
1204                                           (unless force-ipv4
1205                                             (message "Connection timed out. Retrying with IPv4 address.")
1206                                             (elpher-get-finger-page renderer t))))))))
1207             (setq elpher-network-timer timer)
1208             (set-process-coding-system proc 'binary)
1209             (set-process-filter proc
1210                                 (lambda (_proc string)
1211                                   (when timer
1212                                     (cancel-timer timer)
1213                                     (setq timer nil))
1214                                   (setq selector-string-parts
1215                                         (cons string selector-string-parts))))
1216             (set-process-sentinel proc
1217                                   (lambda (_proc event)
1218                                     (condition-case the-error
1219                                         (cond
1220                                          ((string-prefix-p "deleted" event))
1221                                          ((string-prefix-p "open" event)
1222                                           (let ((inhibit-eol-conversion t))
1223                                             (process-send-string
1224                                              proc
1225                                              (concat user "\r\n"))))
1226                                          (t
1227                                           (when timer
1228                                             (cancel-timer timer)
1229                                             (setq timer nil))
1230                                           (funcall renderer (apply #'concat
1231                                                                    (reverse selector-string-parts)))
1232                                           (elpher-restore-pos)))))))
1233         (error
1234          (elpher-network-error address the-error))))))
1235
1236
1237 ;; Other URL page opening
1238
1239 (defun elpher-get-other-url-page (renderer)
1240   "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1241   (when renderer
1242     (elpher-visit-previous-page)
1243     (error "Command not supported for general URLs"))
1244   (let* ((address (elpher-page-address elpher-current-page))
1245          (url (elpher-address-to-url address)))
1246     (progn
1247       (elpher-visit-previous-page) ; Do first in case of non-local exits.
1248       (message "Opening URL...")
1249       (if elpher-open-urls-with-eww
1250           (browse-web url)
1251         (browse-url url)))))
1252
1253 ;; Telnet page connection
1254
1255 (defun elpher-get-telnet-page (renderer)
1256   "Opens a telnet connection to the current page address (RENDERER must be nil)."
1257   (when renderer
1258     (elpher-visit-previous-page)
1259     (error "Command not supported for telnet URLs"))
1260   (let* ((address (elpher-page-address elpher-current-page))
1261          (host (elpher-address-host address))
1262          (port (elpher-address-port address)))
1263     (elpher-visit-previous-page)
1264     (if (> port 0)
1265         (telnet host port)
1266       (telnet host))))
1267
1268 ;; Start page page retrieval
1269
1270 (defun elpher-get-start-page (renderer)
1271   "Getter which displays the start page (RENDERER must be nil)."
1272   (when renderer
1273     (elpher-visit-previous-page)
1274     (error "Command not supported for start page"))
1275   (elpher-with-clean-buffer
1276    (insert "     --------------------------------------------\n"
1277            "           Elpher Gopher and Gemini Client       \n"
1278            "                   version " elpher-version "\n"
1279            "     --------------------------------------------\n"
1280            "\n"
1281            "Default bindings:\n"
1282            "\n"
1283            " - TAB/Shift-TAB: next/prev item on current page\n"
1284            " - RET/mouse-1: open item under cursor\n"
1285            " - m: select an item on current page by name (autocompletes)\n"
1286            " - u/mouse-3: return to previous page\n"
1287            " - o/O: visit different selector or the root menu of the current server\n"
1288            " - g: go to a particular address (gopher, gemini, finger)\n"
1289            " - d/D: download item under cursor or current page\n"
1290            " - i/I: info on item under cursor or current page\n"
1291            " - c/C: copy URL representation of item under cursor or current page\n"
1292            " - a/A: bookmark the item under cursor or current page\n"
1293            " - x/X: remove bookmark for item under cursor or current page\n"
1294            " - B: visit the bookmarks page\n"
1295            " - r: redraw current page (using cached contents if available)\n"
1296            " - R: reload current page (regenerates cache)\n"
1297            " - S: set character coding system for gopher (default is to autodetect)\n"
1298            " - T: toggle TLS gopher mode\n"
1299            " - .: display the raw server response for the current page\n"
1300            "\n"
1301            "Start your exploration of gopher space and gemini:\n")
1302    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1303                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1304    (elpher-insert-index-record "Project Gemini home page"
1305                                (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1306    (insert "\n"
1307            "Alternatively, select a search engine and enter some search terms:\n")
1308    (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1309                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1310    (elpher-insert-index-record "Gemini Search Engine (GUS)"
1311                                (elpher-address-from-url "gemini://gus.guru/search"))
1312    (insert "\n"
1313            "This page contains your bookmarked sites (also visit with B):\n")
1314    (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1315    (insert "\n"
1316            "For Elpher release news or to leave feedback, visit:\n")
1317    (elpher-insert-index-record "The Elpher Project Page"
1318                                (elpher-make-gopher-address ?1
1319                                                            "/projects/elpher/"
1320                                                            "thelambdalab.xyz"
1321                                                            70))
1322    (insert "\n"
1323            "** Refer to the ")
1324    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1325      (insert-text-button "Elpher info manual"
1326                          'face 'link
1327                          'action (lambda (_)
1328                                    (interactive)
1329                                    (info "(elpher)"))
1330                          'follow-link t
1331                          'help-echo help-string))
1332    (insert " for the full documentation. **\n")
1333    (insert (propertize
1334             (concat "  (This should be available if you have installed Elpher using\n"
1335                     "   MELPA. Otherwise you will have to install the manual yourself.)\n")
1336             'face 'shadow))
1337    (elpher-restore-pos)))
1338
1339 ;; Bookmarks page page retrieval
1340
1341 (defun elpher-get-bookmarks-page (renderer)
1342   "Getter to load and display the current bookmark list (RENDERER must be nil)."
1343   (when renderer
1344     (elpher-visit-previous-page)
1345     (error "Command not supported for bookmarks page"))
1346   (elpher-with-clean-buffer
1347    (insert "---- Bookmark list ----\n\n")
1348    (let ((bookmarks (elpher-load-bookmarks)))
1349      (if bookmarks
1350          (dolist (bookmark bookmarks)
1351            (let ((display-string (elpher-bookmark-display-string bookmark))
1352                  (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1353              (elpher-insert-index-record display-string address)))
1354        (insert "No bookmarks found.\n")))
1355    (insert "\n-----------------------\n"
1356            "\n"
1357            "- u: return to previous page\n"
1358            "- x: delete selected bookmark\n"
1359            "- a: rename selected bookmark\n"
1360            "\n"
1361            "Bookmarks are stored in the file ")
1362    (let ((filename elpher-bookmarks-file)
1363          (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1364      (insert-text-button filename
1365                          'face 'link
1366                          'action (lambda (_)
1367                                    (interactive)
1368                                    (find-file filename))
1369                          'follow-link t
1370                          'help-echo help-string))
1371    (insert "\n")
1372    (elpher-restore-pos)))
1373   
1374
1375 ;;; Bookmarks
1376 ;;
1377
1378 (defun elpher-make-bookmark (display-string url)
1379   "Make an elpher bookmark.
1380 DISPLAY-STRING determines how the bookmark will appear in the
1381 bookmark list, while URL is the url of the entry."
1382   (list display-string url))
1383   
1384 (defun elpher-bookmark-display-string (bookmark)
1385   "Get the display string of BOOKMARK."
1386   (elt bookmark 0))
1387
1388 (defun elpher-set-bookmark-display-string (bookmark display-string)
1389   "Set the display string of BOOKMARK to DISPLAY-STRING."
1390   (setcar bookmark display-string))
1391
1392 (defun elpher-bookmark-url (bookmark)
1393   "Get the address for BOOKMARK."
1394   (elt bookmark 1))
1395
1396 (defun elpher-save-bookmarks (bookmarks)
1397   "Record the bookmark list BOOKMARKS to the user's bookmark file.
1398 Beware that this completely replaces the existing contents of the file."
1399   (with-temp-file elpher-bookmarks-file
1400     (erase-buffer)
1401     (insert "; Elpher bookmarks file\n\n"
1402             "; Bookmarks are stored as a list of (label URL) items.\n"
1403             "; Feel free to edit by hand, but take care to ensure\n"
1404             "; the list structure remains intact.\n\n")
1405     (pp bookmarks (current-buffer))))
1406
1407 (defun elpher-load-bookmarks ()
1408   "Get the list of bookmarks from the users's bookmark file."
1409   (let ((bookmarks
1410          (with-temp-buffer
1411            (ignore-errors
1412              (insert-file-contents elpher-bookmarks-file)
1413              (goto-char (point-min))
1414              (read (current-buffer))))))
1415     (if (and bookmarks (listp (cadar bookmarks)))
1416         (progn
1417           (message "Reading old bookmark file. (Will be updated on write.)")
1418           (mapcar (lambda (old-bm)
1419                     (list (car old-bm)
1420                           (elpher-address-to-url (apply #'elpher-make-gopher-address
1421                                                         (cadr old-bm)))))
1422                   bookmarks))
1423       bookmarks)))
1424
1425 (defun elpher-add-address-bookmark (address display-string)
1426   "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1427 If ADDRESS is already bookmarked, update the label only."
1428   (let ((bookmarks (elpher-load-bookmarks))
1429         (url (elpher-address-to-url address)))
1430     (let ((existing-bookmark (rassoc (list url) bookmarks)))
1431       (if existing-bookmark
1432           (elpher-set-bookmark-display-string existing-bookmark display-string)
1433         (push (elpher-make-bookmark display-string url) bookmarks)))
1434     (elpher-save-bookmarks bookmarks)))
1435
1436 (defun elpher-remove-address-bookmark (address)
1437   "Remove any bookmark to ADDRESS."
1438   (let ((url (elpher-address-to-url address)))
1439     (elpher-save-bookmarks
1440      (seq-filter (lambda (bookmark)
1441                    (not (equal (elpher-bookmark-url bookmark) url)))
1442                  (elpher-load-bookmarks)))))
1443
1444 ;;; Interactive procedures
1445 ;;
1446
1447 (defun elpher-next-link ()
1448   "Move point to the next link on the current page."
1449   (interactive)
1450   (forward-button 1))
1451
1452 (defun elpher-prev-link ()
1453   "Move point to the previous link on the current page."
1454   (interactive)
1455   (backward-button 1))
1456
1457 (defun elpher-follow-current-link ()
1458   "Open the link or url at point."
1459   (interactive)
1460   (push-button))
1461
1462 (defun elpher-go (host-or-url)
1463   "Go to a particular gopher site HOST-OR-URL.
1464 When run interactively HOST-OR-URL is read from the minibuffer."
1465   (interactive "sGopher or Gemini URL: ")
1466   (let ((page (elpher-make-page host-or-url
1467                                 (elpher-address-from-url host-or-url))))
1468     (switch-to-buffer "*elpher*")
1469     (elpher-visit-page page)
1470     '()))
1471
1472 (defun elpher-go-current ()
1473   "Go to a particular site read from the minibuffer, initialized with the current URL."
1474   (interactive)
1475   (let ((address (elpher-page-address elpher-current-page)))
1476     (if (elpher-address-special-p address)
1477         (error "Command invalid for this page")
1478       (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1479         (elpher-visit-page (elpher-make-page url (elpher-address-from-url url)))))))
1480
1481 (defun elpher-redraw ()
1482   "Redraw current page."
1483   (interactive)
1484   (elpher-visit-page elpher-current-page))
1485
1486 (defun elpher-reload ()
1487   "Reload current page."
1488   (interactive)
1489   (elpher-reload-current-page))
1490
1491 (defun elpher-toggle-tls ()
1492   "Toggle TLS encryption mode for gopher."
1493   (interactive)
1494   (setq elpher-use-tls (not elpher-use-tls))
1495   (if elpher-use-tls
1496       (if (gnutls-available-p)
1497           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
1498         (setq elpher-use-tls nil)
1499         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1500     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
1501
1502 (defun elpher-view-raw ()
1503   "View raw server response for current page."
1504   (interactive)
1505   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1506       (error "This page was not generated by a server")
1507     (elpher-visit-page elpher-current-page
1508                        #'elpher-render-raw)))
1509
1510 (defun elpher-back ()
1511   "Go to previous site."
1512   (interactive)
1513   (elpher-visit-previous-page))
1514
1515 (defun elpher-download ()
1516   "Download the link at point."
1517   (interactive)
1518   (let ((button (button-at (point))))
1519     (if button
1520         (let ((page (button-get button 'elpher-page)))
1521           (if (elpher-address-special-p (elpher-page-address page))
1522               (error "Cannot download %s"
1523                      (elpher-page-display-string page))
1524             (elpher-visit-page (button-get button 'elpher-page)
1525                                #'elpher-render-download)))
1526       (error "No link selected"))))
1527
1528 (defun elpher-download-current ()
1529   "Download the current page."
1530   (interactive)
1531   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1532       (error "Cannot download %s"
1533              (elpher-page-display-string elpher-current-page))
1534     (elpher-visit-page (elpher-make-page
1535                         (elpher-page-display-string elpher-current-page)
1536                         (elpher-page-address elpher-current-page))
1537                        #'elpher-render-download
1538                        t)))
1539
1540 (defun elpher-build-link-map ()
1541   "Build alist mapping link names to destination pages in current buffer."
1542   (let ((link-map nil)
1543         (b (next-button (point-min) t)))
1544     (while b
1545       (push (cons (button-label b) b) link-map)
1546       (setq b (next-button (button-start b))))
1547     link-map))
1548
1549 (defun elpher-jump ()
1550   "Select a directory entry by name.  Similar to the info browser (m)enu command."
1551   (interactive)
1552   (let* ((link-map (elpher-build-link-map)))
1553     (if link-map
1554         (let ((key (let ((completion-ignore-case t))
1555                      (completing-read "Directory item/link: "
1556                                       link-map nil t))))
1557           (if (and key (> (length key) 0))
1558               (let ((b (cdr (assoc key link-map))))
1559                 (goto-char (button-start b))
1560                 (button-activate b)))))))
1561
1562 (defun elpher-root-dir ()
1563   "Visit root of current server."
1564   (interactive)
1565   (let ((address (elpher-page-address elpher-current-page)))
1566     (if (not (elpher-address-special-p address))
1567         (if (or (member (url-filename address) '("/" ""))
1568                 (and (elpher-address-gopher-p address)
1569                      (= (length (elpher-gopher-address-selector address)) 0)))
1570             (error "Already at root directory of current server")
1571           (let ((address-copy (elpher-address-from-url
1572                                (elpher-address-to-url address))))
1573             (setf (url-filename address-copy) "")
1574             (elpher-go (elpher-address-to-url address-copy))))
1575       (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
1576
1577 (defun elpher-bookmarks-current-p ()
1578   "Return non-nil if current page is a bookmarks page."
1579   (equal (elpher-address-type (elpher-page-address elpher-current-page))
1580          '(special bookmarks)))
1581
1582 (defun elpher-reload-bookmarks ()
1583   "Reload bookmarks if current page is a bookmarks page."
1584   (if (elpher-bookmarks-current-p)
1585       (elpher-reload-current-page)))
1586
1587 (defun elpher-bookmark-current ()
1588   "Bookmark the current page."
1589   (interactive)
1590   (let ((address (elpher-page-address elpher-current-page))
1591         (display-string (elpher-page-display-string elpher-current-page)))
1592     (if (not (elpher-address-special-p address))
1593         (let ((bookmark-display-string (read-string "Bookmark display string: "
1594                                                     display-string)))
1595           (elpher-add-address-bookmark address bookmark-display-string)
1596           (message "Bookmark added."))
1597       (error "Cannot bookmark %s" display-string))))
1598
1599 (defun elpher-bookmark-link ()
1600   "Bookmark the link at point."
1601   (interactive)
1602   (let ((button (button-at (point))))
1603     (if button
1604         (let* ((page (button-get button 'elpher-page))
1605                (address (elpher-page-address page))
1606                (display-string (elpher-page-display-string page)))
1607           (if (not (elpher-address-special-p address))
1608               (let ((bookmark-display-string (read-string "Bookmark display string: "
1609                                                           display-string)))
1610                 (elpher-add-address-bookmark address bookmark-display-string)
1611                 (elpher-reload-bookmarks)
1612                 (message "Bookmark added."))
1613             (error "Cannot bookmark %s" display-string)))
1614       (error "No link selected"))))
1615
1616 (defun elpher-unbookmark-current ()
1617   "Remove bookmark for the current page."
1618   (interactive)
1619   (let ((address (elpher-page-address elpher-current-page)))
1620     (unless (elpher-address-special-p address)
1621       (elpher-remove-address-bookmark address)
1622       (message "Bookmark removed."))))
1623
1624 (defun elpher-unbookmark-link ()
1625   "Remove bookmark for the link at point."
1626   (interactive)
1627   (let ((button (button-at (point))))
1628     (if button
1629         (let ((page (button-get button 'elpher-page)))
1630           (elpher-remove-address-bookmark (elpher-page-address page))
1631           (elpher-reload-bookmarks)
1632           (message "Bookmark removed."))
1633       (error "No link selected"))))
1634
1635 (defun elpher-bookmarks ()
1636   "Visit bookmarks page."
1637   (interactive)
1638   (switch-to-buffer "*elpher*")
1639   (elpher-visit-page
1640    (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
1641
1642 (defun elpher-info-page (page)
1643   "Display information on PAGE."
1644   (let ((display-string (elpher-page-display-string page))
1645         (address (elpher-page-address page)))
1646     (if (elpher-address-special-p address)
1647         (message "Special page: %s" display-string)
1648       (message "%s" (elpher-address-to-url address)))))
1649
1650 (defun elpher-info-link ()
1651   "Display information on page corresponding to link at point."
1652   (interactive)
1653   (let ((button (button-at (point))))
1654     (if button
1655         (elpher-info-page (button-get button 'elpher-page))
1656       (error "No item selected"))))
1657   
1658 (defun elpher-info-current ()
1659   "Display information on current page."
1660   (interactive)
1661   (elpher-info-page elpher-current-page))
1662
1663 (defun elpher-copy-page-url (page)
1664   "Copy URL representation of address of PAGE to `kill-ring'."
1665   (let ((address (elpher-page-address page)))
1666     (if (elpher-address-special-p address)
1667         (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
1668       (let ((url (elpher-address-to-url address)))
1669         (message "Copied \"%s\" to kill-ring/clipboard." url)
1670         (kill-new url)))))
1671
1672 (defun elpher-copy-link-url ()
1673   "Copy URL of item at point to `kill-ring'."
1674   (interactive)
1675   (let ((button (button-at (point))))
1676     (if button
1677         (elpher-copy-page-url (button-get button 'elpher-page))
1678       (error "No item selected"))))
1679
1680 (defun elpher-copy-current-url ()
1681   "Copy URL of current page to `kill-ring'."
1682   (interactive)
1683   (elpher-copy-page-url elpher-current-page))
1684
1685 (defun elpher-set-gopher-coding-system ()
1686   "Specify an explicit character coding system for gopher selectors."
1687   (interactive)
1688   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
1689     (setq elpher-user-coding-system system)
1690     (if system
1691         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
1692       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
1693
1694
1695 ;;; Mode and keymap
1696 ;;
1697
1698 (defvar elpher-mode-map
1699   (let ((map (make-sparse-keymap)))
1700     (define-key map (kbd "TAB") 'elpher-next-link)
1701     (define-key map (kbd "<backtab>") 'elpher-prev-link)
1702     (define-key map (kbd "C-M-i") 'elpher-prev-link)
1703     (define-key map (kbd "u") 'elpher-back)
1704     (define-key map [mouse-3] 'elpher-back)
1705     (define-key map (kbd "O") 'elpher-root-dir)
1706     (define-key map (kbd "g") 'elpher-go)
1707     (define-key map (kbd "o") 'elpher-go-current)
1708     (define-key map (kbd "r") 'elpher-redraw)
1709     (define-key map (kbd "R") 'elpher-reload)
1710     (define-key map (kbd "T") 'elpher-toggle-tls)
1711     (define-key map (kbd ".") 'elpher-view-raw)
1712     (define-key map (kbd "d") 'elpher-download)
1713     (define-key map (kbd "D") 'elpher-download-current)
1714     (define-key map (kbd "m") 'elpher-jump)
1715     (define-key map (kbd "i") 'elpher-info-link)
1716     (define-key map (kbd "I") 'elpher-info-current)
1717     (define-key map (kbd "c") 'elpher-copy-link-url)
1718     (define-key map (kbd "C") 'elpher-copy-current-url)
1719     (define-key map (kbd "a") 'elpher-bookmark-link)
1720     (define-key map (kbd "A") 'elpher-bookmark-current)
1721     (define-key map (kbd "x") 'elpher-unbookmark-link)
1722     (define-key map (kbd "X") 'elpher-unbookmark-current)
1723     (define-key map (kbd "B") 'elpher-bookmarks)
1724     (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
1725     (when (fboundp 'evil-define-key*)
1726       (evil-define-key* 'motion map
1727         (kbd "TAB") 'elpher-next-link
1728         (kbd "C-") 'elpher-follow-current-link
1729         (kbd "C-t") 'elpher-back
1730         (kbd "u") 'elpher-back
1731         [mouse-3] 'elpher-back
1732         (kbd "g") 'elpher-go
1733         (kbd "o") 'elpher-go-current
1734         (kbd "r") 'elpher-redraw
1735         (kbd "R") 'elpher-reload
1736         (kbd "T") 'elpher-toggle-tls
1737         (kbd ".") 'elpher-view-raw
1738         (kbd "d") 'elpher-download
1739         (kbd "D") 'elpher-download-current
1740         (kbd "m") 'elpher-jump
1741         (kbd "i") 'elpher-info-link
1742         (kbd "I") 'elpher-info-current
1743         (kbd "c") 'elpher-copy-link-url
1744         (kbd "C") 'elpher-copy-current-url
1745         (kbd "a") 'elpher-bookmark-link
1746         (kbd "A") 'elpher-bookmark-current
1747         (kbd "x") 'elpher-unbookmark-link
1748         (kbd "X") 'elpher-unbookmark-current
1749         (kbd "B") 'elpher-bookmarks
1750         (kbd "S") 'elpher-set-gopher-coding-system))
1751     map)
1752   "Keymap for gopher client.")
1753
1754 (define-derived-mode elpher-mode special-mode "elpher"
1755   "Major mode for elpher, an elisp gopher client.
1756
1757 This mode is automatically enabled by the interactive
1758 functions which initialize the gopher client, namely
1759 `elpher', `elpher-go' and `elpher-bookmarks'.")
1760
1761 (when (fboundp 'evil-set-initial-state)
1762   (evil-set-initial-state 'elpher-mode 'motion))
1763
1764
1765 ;;; Main start procedure
1766 ;;
1767
1768 ;;;###autoload
1769 (defun elpher ()
1770   "Start elpher with default landing page."
1771   (interactive)
1772   (if (get-buffer "*elpher*")
1773       (switch-to-buffer "*elpher*")
1774     (switch-to-buffer "*elpher*")
1775     (setq elpher-current-page nil)
1776     (let ((start-page (elpher-make-page "Elpher Start Page"
1777                                         (elpher-make-special-address 'start))))
1778       (elpher-visit-page start-page)))
1779   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
1780
1781 ;;; elpher.el ends here