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