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