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