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