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