Merge remote-tracking branch 'origin/patch_gus'
[elpher.git] / elpher.el
1 ;;; elpher.el --- A friendly gopher 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.4
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, gemini,
30 ;; and finger 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 ;; - 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.4"
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 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:\n")
1300    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1301                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1302    (insert "\n"
1303            "Alternatively, select a search engine and enter some search terms:\n")
1304    (elpher-insert-index-record "Veronica-2 Gopher Search Engine"
1305                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1306    (elpher-insert-index-record "GUS Gemini Search Engine"
1307                                (elpher-address-from-url "gemini://gus.guru/search"))
1308    (insert "\n"
1309            "This page contains your bookmarked sites (also visit with B):\n")
1310    (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1311    (insert "\n"
1312            "For Elpher release news or to leave feedback, visit:\n")
1313    (elpher-insert-index-record "The Elpher Project Page"
1314                                (elpher-make-gopher-address ?1
1315                                                            "/projects/elpher/"
1316                                                            "thelambdalab.xyz"
1317                                                            70))
1318    (insert "\n"
1319            "** Refer to the ")
1320    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1321      (insert-text-button "Elpher info manual"
1322                          'face 'link
1323                          'action (lambda (_)
1324                                    (interactive)
1325                                    (info "(elpher)"))
1326                          'follow-link t
1327                          'help-echo help-string))
1328    (insert " for the full documentation. **\n")
1329    (insert (propertize
1330             (concat "  (This should be available if you have installed Elpher using\n"
1331                     "   MELPA. Otherwise you will have to install the manual yourself.)\n")
1332             'face 'shadow))
1333    (elpher-restore-pos)))
1334
1335 ;; Bookmarks page page retrieval
1336
1337 (defun elpher-get-bookmarks-page (renderer)
1338   "Getter to load and display the current bookmark list (RENDERER must be nil)."
1339   (when renderer
1340     (elpher-visit-previous-page)
1341     (error "Command not supported for bookmarks page"))
1342   (elpher-with-clean-buffer
1343    (insert "---- Bookmark list ----\n\n")
1344    (let ((bookmarks (elpher-load-bookmarks)))
1345      (if bookmarks
1346          (dolist (bookmark bookmarks)
1347            (let ((display-string (elpher-bookmark-display-string bookmark))
1348                  (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1349              (elpher-insert-index-record display-string address)))
1350        (insert "No bookmarks found.\n")))
1351    (insert "\n-----------------------\n"
1352            "\n"
1353            "- u: return to previous page\n"
1354            "- x: delete selected bookmark\n"
1355            "- a: rename selected bookmark\n"
1356            "\n"
1357            "Bookmarks are stored in the file ")
1358    (let ((filename elpher-bookmarks-file)
1359          (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1360      (insert-text-button filename
1361                          'face 'link
1362                          'action (lambda (_)
1363                                    (interactive)
1364                                    (find-file filename))
1365                          'follow-link t
1366                          'help-echo help-string))
1367    (insert "\n")
1368    (elpher-restore-pos)))
1369   
1370
1371 ;;; Bookmarks
1372 ;;
1373
1374 (defun elpher-make-bookmark (display-string url)
1375   "Make an elpher bookmark.
1376 DISPLAY-STRING determines how the bookmark will appear in the
1377 bookmark list, while URL is the url of the entry."
1378   (list display-string url))
1379   
1380 (defun elpher-bookmark-display-string (bookmark)
1381   "Get the display string of BOOKMARK."
1382   (elt bookmark 0))
1383
1384 (defun elpher-set-bookmark-display-string (bookmark display-string)
1385   "Set the display string of BOOKMARK to DISPLAY-STRING."
1386   (setcar bookmark display-string))
1387
1388 (defun elpher-bookmark-url (bookmark)
1389   "Get the address for BOOKMARK."
1390   (elt bookmark 1))
1391
1392 (defun elpher-save-bookmarks (bookmarks)
1393   "Record the bookmark list BOOKMARKS to the user's bookmark file.
1394 Beware that this completely replaces the existing contents of the file."
1395   (with-temp-file elpher-bookmarks-file
1396     (erase-buffer)
1397     (insert "; Elpher bookmarks file\n\n"
1398             "; Bookmarks are stored as a list of (label URL) items.\n"
1399             "; Feel free to edit by hand, but take care to ensure\n"
1400             "; the list structure remains intact.\n\n")
1401     (pp bookmarks (current-buffer))))
1402
1403 (defun elpher-load-bookmarks ()
1404   "Get the list of bookmarks from the users's bookmark file."
1405   (let ((bookmarks
1406          (with-temp-buffer
1407            (ignore-errors
1408              (insert-file-contents elpher-bookmarks-file)
1409              (goto-char (point-min))
1410              (read (current-buffer))))))
1411     (if (and bookmarks (listp (cadar bookmarks)))
1412         (progn
1413           (message "Reading old bookmark file. (Will be updated on write.)")
1414           (mapcar (lambda (old-bm)
1415                     (list (car old-bm)
1416                           (elpher-address-to-url (apply #'elpher-make-gopher-address
1417                                                         (cadr old-bm)))))
1418                   bookmarks))
1419       bookmarks)))
1420
1421 (defun elpher-add-address-bookmark (address display-string)
1422   "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1423 If ADDRESS is already bookmarked, update the label only."
1424   (let ((bookmarks (elpher-load-bookmarks))
1425         (url (elpher-address-to-url address)))
1426     (let ((existing-bookmark (rassoc (list url) bookmarks)))
1427       (if existing-bookmark
1428           (elpher-set-bookmark-display-string existing-bookmark display-string)
1429         (push (elpher-make-bookmark display-string url) bookmarks)))
1430     (elpher-save-bookmarks bookmarks)))
1431
1432 (defun elpher-remove-address-bookmark (address)
1433   "Remove any bookmark to ADDRESS."
1434   (let ((url (elpher-address-to-url address)))
1435     (elpher-save-bookmarks
1436      (seq-filter (lambda (bookmark)
1437                    (not (equal (elpher-bookmark-url bookmark) url)))
1438                  (elpher-load-bookmarks)))))
1439
1440 ;;; Interactive procedures
1441 ;;
1442
1443 (defun elpher-next-link ()
1444   "Move point to the next link on the current page."
1445   (interactive)
1446   (forward-button 1))
1447
1448 (defun elpher-prev-link ()
1449   "Move point to the previous link on the current page."
1450   (interactive)
1451   (backward-button 1))
1452
1453 (defun elpher-follow-current-link ()
1454   "Open the link or url at point."
1455   (interactive)
1456   (push-button))
1457
1458 (defun elpher-go (host-or-url)
1459   "Go to a particular gopher site HOST-OR-URL.
1460 When run interactively HOST-OR-URL is read from the minibuffer."
1461   (interactive "sGopher or Gemini URL: ")
1462   (let ((page (elpher-make-page host-or-url
1463                                 (elpher-address-from-url host-or-url))))
1464     (switch-to-buffer "*elpher*")
1465     (elpher-visit-page page)
1466     '()))
1467
1468 (defun elpher-go-current ()
1469   "Go to a particular site read from the minibuffer, initialized with the current URL."
1470   (interactive)
1471   (let ((address (elpher-page-address elpher-current-page)))
1472     (if (elpher-address-special-p address)
1473         (error "Command invalid for this page")
1474       (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1475         (elpher-visit-page (elpher-make-page url (elpher-address-from-url url)))))))
1476
1477 (defun elpher-redraw ()
1478   "Redraw current page."
1479   (interactive)
1480   (elpher-visit-page elpher-current-page))
1481
1482 (defun elpher-reload ()
1483   "Reload current page."
1484   (interactive)
1485   (elpher-reload-current-page))
1486
1487 (defun elpher-toggle-tls ()
1488   "Toggle TLS encryption mode for gopher."
1489   (interactive)
1490   (setq elpher-use-tls (not elpher-use-tls))
1491   (if elpher-use-tls
1492       (if (gnutls-available-p)
1493           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
1494         (setq elpher-use-tls nil)
1495         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1496     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
1497
1498 (defun elpher-view-raw ()
1499   "View raw server response for current page."
1500   (interactive)
1501   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1502       (error "This page was not generated by a server")
1503     (elpher-visit-page elpher-current-page
1504                        #'elpher-render-raw)))
1505
1506 (defun elpher-back ()
1507   "Go to previous site."
1508   (interactive)
1509   (elpher-visit-previous-page))
1510
1511 (defun elpher-download ()
1512   "Download the link at point."
1513   (interactive)
1514   (let ((button (button-at (point))))
1515     (if button
1516         (let ((page (button-get button 'elpher-page)))
1517           (if (elpher-address-special-p (elpher-page-address page))
1518               (error "Cannot download %s"
1519                      (elpher-page-display-string page))
1520             (elpher-visit-page (button-get button 'elpher-page)
1521                                #'elpher-render-download)))
1522       (error "No link selected"))))
1523
1524 (defun elpher-download-current ()
1525   "Download the current page."
1526   (interactive)
1527   (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1528       (error "Cannot download %s"
1529              (elpher-page-display-string elpher-current-page))
1530     (elpher-visit-page (elpher-make-page
1531                         (elpher-page-display-string elpher-current-page)
1532                         (elpher-page-address elpher-current-page))
1533                        #'elpher-render-download
1534                        t)))
1535
1536 (defun elpher-build-link-map ()
1537   "Build alist mapping link names to destination pages in current buffer."
1538   (let ((link-map nil)
1539         (b (next-button (point-min) t)))
1540     (while b
1541       (push (cons (button-label b) b) link-map)
1542       (setq b (next-button (button-start b))))
1543     link-map))
1544
1545 (defun elpher-jump ()
1546   "Select a directory entry by name.  Similar to the info browser (m)enu command."
1547   (interactive)
1548   (let* ((link-map (elpher-build-link-map)))
1549     (if link-map
1550         (let ((key (let ((completion-ignore-case t))
1551                      (completing-read "Directory item/link: "
1552                                       link-map nil t))))
1553           (if (and key (> (length key) 0))
1554               (let ((b (cdr (assoc key link-map))))
1555                 (goto-char (button-start b))
1556                 (button-activate b)))))))
1557
1558 (defun elpher-root-dir ()
1559   "Visit root of current server."
1560   (interactive)
1561   (let ((address (elpher-page-address elpher-current-page)))
1562     (if (not (elpher-address-special-p address))
1563         (if (or (member (url-filename address) '("/" ""))
1564                 (and (elpher-address-gopher-p address)
1565                      (= (length (elpher-gopher-address-selector address)) 0)))
1566             (error "Already at root directory of current server")
1567           (let ((address-copy (elpher-address-from-url
1568                                (elpher-address-to-url address))))
1569             (setf (url-filename address-copy) "")
1570             (elpher-go (elpher-address-to-url address-copy))))
1571       (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
1572
1573 (defun elpher-bookmarks-current-p ()
1574   "Return non-nil if current page is a bookmarks page."
1575   (equal (elpher-address-type (elpher-page-address elpher-current-page))
1576          '(special bookmarks)))
1577
1578 (defun elpher-reload-bookmarks ()
1579   "Reload bookmarks if current page is a bookmarks page."
1580   (if (elpher-bookmarks-current-p)
1581       (elpher-reload-current-page)))
1582
1583 (defun elpher-bookmark-current ()
1584   "Bookmark the current page."
1585   (interactive)
1586   (let ((address (elpher-page-address elpher-current-page))
1587         (display-string (elpher-page-display-string elpher-current-page)))
1588     (if (not (elpher-address-special-p address))
1589         (let ((bookmark-display-string (read-string "Bookmark display string: "
1590                                                     display-string)))
1591           (elpher-add-address-bookmark address bookmark-display-string)
1592           (message "Bookmark added."))
1593       (error "Cannot bookmark %s" display-string))))
1594
1595 (defun elpher-bookmark-link ()
1596   "Bookmark the link at point."
1597   (interactive)
1598   (let ((button (button-at (point))))
1599     (if button
1600         (let* ((page (button-get button 'elpher-page))
1601                (address (elpher-page-address page))
1602                (display-string (elpher-page-display-string page)))
1603           (if (not (elpher-address-special-p address))
1604               (let ((bookmark-display-string (read-string "Bookmark display string: "
1605                                                           display-string)))
1606                 (elpher-add-address-bookmark address bookmark-display-string)
1607                 (elpher-reload-bookmarks)
1608                 (message "Bookmark added."))
1609             (error "Cannot bookmark %s" display-string)))
1610       (error "No link selected"))))
1611
1612 (defun elpher-unbookmark-current ()
1613   "Remove bookmark for the current page."
1614   (interactive)
1615   (let ((address (elpher-page-address elpher-current-page)))
1616     (unless (elpher-address-special-p address)
1617       (elpher-remove-address-bookmark address)
1618       (message "Bookmark removed."))))
1619
1620 (defun elpher-unbookmark-link ()
1621   "Remove bookmark for the link at point."
1622   (interactive)
1623   (let ((button (button-at (point))))
1624     (if button
1625         (let ((page (button-get button 'elpher-page)))
1626           (elpher-remove-address-bookmark (elpher-page-address page))
1627           (elpher-reload-bookmarks)
1628           (message "Bookmark removed."))
1629       (error "No link selected"))))
1630
1631 (defun elpher-bookmarks ()
1632   "Visit bookmarks page."
1633   (interactive)
1634   (switch-to-buffer "*elpher*")
1635   (elpher-visit-page
1636    (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
1637
1638 (defun elpher-info-page (page)
1639   "Display information on PAGE."
1640   (let ((display-string (elpher-page-display-string page))
1641         (address (elpher-page-address page)))
1642     (if (elpher-address-special-p address)
1643         (message "Special page: %s" display-string)
1644       (message "%s" (elpher-address-to-url address)))))
1645
1646 (defun elpher-info-link ()
1647   "Display information on page corresponding to link at point."
1648   (interactive)
1649   (let ((button (button-at (point))))
1650     (if button
1651         (elpher-info-page (button-get button 'elpher-page))
1652       (error "No item selected"))))
1653   
1654 (defun elpher-info-current ()
1655   "Display information on current page."
1656   (interactive)
1657   (elpher-info-page elpher-current-page))
1658
1659 (defun elpher-copy-page-url (page)
1660   "Copy URL representation of address of PAGE to `kill-ring'."
1661   (let ((address (elpher-page-address page)))
1662     (if (elpher-address-special-p address)
1663         (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
1664       (let ((url (elpher-address-to-url address)))
1665         (message "Copied \"%s\" to kill-ring/clipboard." url)
1666         (kill-new url)))))
1667
1668 (defun elpher-copy-link-url ()
1669   "Copy URL of item at point to `kill-ring'."
1670   (interactive)
1671   (let ((button (button-at (point))))
1672     (if button
1673         (elpher-copy-page-url (button-get button 'elpher-page))
1674       (error "No item selected"))))
1675
1676 (defun elpher-copy-current-url ()
1677   "Copy URL of current page to `kill-ring'."
1678   (interactive)
1679   (elpher-copy-page-url elpher-current-page))
1680
1681 (defun elpher-set-gopher-coding-system ()
1682   "Specify an explicit character coding system for gopher selectors."
1683   (interactive)
1684   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
1685     (setq elpher-user-coding-system system)
1686     (if system
1687         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
1688       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
1689
1690
1691 ;;; Mode and keymap
1692 ;;
1693
1694 (defvar elpher-mode-map
1695   (let ((map (make-sparse-keymap)))
1696     (define-key map (kbd "TAB") 'elpher-next-link)
1697     (define-key map (kbd "<backtab>") 'elpher-prev-link)
1698     (define-key map (kbd "C-M-i") 'elpher-prev-link)
1699     (define-key map (kbd "u") 'elpher-back)
1700     (define-key map [mouse-3] 'elpher-back)
1701     (define-key map (kbd "O") 'elpher-root-dir)
1702     (define-key map (kbd "g") 'elpher-go)
1703     (define-key map (kbd "o") 'elpher-go-current)
1704     (define-key map (kbd "r") 'elpher-redraw)
1705     (define-key map (kbd "R") 'elpher-reload)
1706     (define-key map (kbd "T") 'elpher-toggle-tls)
1707     (define-key map (kbd ".") 'elpher-view-raw)
1708     (define-key map (kbd "d") 'elpher-download)
1709     (define-key map (kbd "D") 'elpher-download-current)
1710     (define-key map (kbd "m") 'elpher-jump)
1711     (define-key map (kbd "i") 'elpher-info-link)
1712     (define-key map (kbd "I") 'elpher-info-current)
1713     (define-key map (kbd "c") 'elpher-copy-link-url)
1714     (define-key map (kbd "C") 'elpher-copy-current-url)
1715     (define-key map (kbd "a") 'elpher-bookmark-link)
1716     (define-key map (kbd "A") 'elpher-bookmark-current)
1717     (define-key map (kbd "x") 'elpher-unbookmark-link)
1718     (define-key map (kbd "X") 'elpher-unbookmark-current)
1719     (define-key map (kbd "B") 'elpher-bookmarks)
1720     (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
1721     (when (fboundp 'evil-define-key*)
1722       (evil-define-key* 'motion map
1723         (kbd "TAB") 'elpher-next-link
1724         (kbd "C-") 'elpher-follow-current-link
1725         (kbd "C-t") 'elpher-back
1726         (kbd "u") 'elpher-back
1727         [mouse-3] 'elpher-back
1728         (kbd "g") 'elpher-go
1729         (kbd "o") 'elpher-go-current
1730         (kbd "r") 'elpher-redraw
1731         (kbd "R") 'elpher-reload
1732         (kbd "T") 'elpher-toggle-tls
1733         (kbd ".") 'elpher-view-raw
1734         (kbd "d") 'elpher-download
1735         (kbd "D") 'elpher-download-current
1736         (kbd "m") 'elpher-jump
1737         (kbd "i") 'elpher-info-link
1738         (kbd "I") 'elpher-info-current
1739         (kbd "c") 'elpher-copy-link-url
1740         (kbd "C") 'elpher-copy-current-url
1741         (kbd "a") 'elpher-bookmark-link
1742         (kbd "A") 'elpher-bookmark-current
1743         (kbd "x") 'elpher-unbookmark-link
1744         (kbd "X") 'elpher-unbookmark-current
1745         (kbd "B") 'elpher-bookmarks
1746         (kbd "S") 'elpher-set-gopher-coding-system))
1747     map)
1748   "Keymap for gopher client.")
1749
1750 (define-derived-mode elpher-mode special-mode "elpher"
1751   "Major mode for elpher, an elisp gopher client.
1752
1753 This mode is automatically enabled by the interactive
1754 functions which initialize the gopher client, namely
1755 `elpher', `elpher-go' and `elpher-bookmarks'.")
1756
1757 (when (fboundp 'evil-set-initial-state)
1758   (evil-set-initial-state 'elpher-mode 'motion))
1759
1760
1761 ;;; Main start procedure
1762 ;;
1763
1764 ;;;###autoload
1765 (defun elpher ()
1766   "Start elpher with default landing page."
1767   (interactive)
1768   (if (get-buffer "*elpher*")
1769       (switch-to-buffer "*elpher*")
1770     (switch-to-buffer "*elpher*")
1771     (setq elpher-current-page nil)
1772     (let ((start-page (elpher-make-page "Elpher Start Page"
1773                                         (elpher-make-special-address 'start))))
1774       (elpher-visit-page start-page)))
1775   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
1776
1777 ;;; elpher.el ends here