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