Merge branch 'nowait'
[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.3.6
8 ;; Keywords: comm gopher
9 ;; Homepage: https://github.com/tgvaughan/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.3.6"
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 (defun elpher-process-cleanup ()
486   "Immediately shut down any extant elpher process and timers."
487   (let ((p (get-process "elpher-process")))
488     (if p (delete-process p)))
489   (if (timerp elpher-network-timer)
490       (cancel-timer elpher-network-timer)))
491
492 (defvar elpher-use-tls nil
493   "If non-nil, use TLS to communicate with gopher servers.")
494
495 (defvar elpher-network-timer)
496
497 (defun elpher-get-selector (address renderer &optional force-ipv4)
498   "Retrieve selector specified by ADDRESS, then render it using RENDERER.
499 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
500 to ADDRESS."
501   (when (equal (elpher-address-protocol address) "gophers")
502     (if (gnutls-available-p)
503         (when (not elpher-use-tls)
504           (setq elpher-use-tls t)
505           (message "Engaging TLS gopher mode."))
506       (elpher-network-error "Cannot retrieve TLS gopher selector: GnuTLS not available")))
507   (unless (< (elpher-address-port address) 65536)
508     (elpher-network-error "Cannot retrieve gopher selector: port number > 65536"))
509   (let* ((kill-buffer-query-functions nil)
510          (port (elpher-address-port address))
511          (host (elpher-address-host address))
512          (selector-string "")
513          (proc (open-network-stream "elpher-process"
514                                     nil
515                                     (if force-ipv4 (dns-query host) host)
516                                     (if (> port 0) port 70)
517                                     :type (if elpher-use-tls 'tls 'plain)
518                                     :nowait t))
519          (timer (run-at-time elpher-connection-timeout
520                              nil
521                              (lambda ()
522                                (pcase (process-status proc)
523                                  ('failed
524                                   (if (and (not (equal (elpher-address-protocol address)
525                                                        "gophers"))
526                                            elpher-use-tls
527                                            (or elpher-auto-disengage-TLS
528                                                (yes-or-no-p "Could not establish encrypted connection.  Disable TLS mode?")))
529                                       (progn
530                                         (message "Disabling TLS mode.")
531                                         (setq elpher-use-tls nil)
532                                         (elpher-get-selector address renderer))
533                                     (elpher-network-error "Could not establish encrypted connection.")))
534                                  ('connect
535                                   (elpher-process-cleanup)
536                                   (unless force-ipv4
537                                     (message "Connection timed out. Retrying with IPv4 address.")
538                                     (elpher-get-selector address renderer t))))))))
539     (setq elpher-network-timer timer)
540     (set-process-coding-system proc 'binary)
541     (set-process-filter proc
542                         (lambda (_proc string)
543                           (cancel-timer timer)
544                           (setq selector-string
545                                 (concat selector-string string))))
546     (set-process-sentinel proc
547                           (lambda (_proc event)
548                             (condition-case the-error
549                                 (cond
550                                  ((string-prefix-p "deleted" event))
551                                  ((string-prefix-p "open" event)
552                                   (let ((inhibit-eol-conversion t))
553                                     (process-send-string
554                                      proc
555                                      (concat (elpher-gopher-address-selector address)
556                                              "\r\n"))))
557                                  (t
558                                   (cancel-timer timer)
559                                   (funcall renderer selector-string)
560                                   (elpher-restore-pos)))
561                               (error
562                                (elpher-network-error address
563                                                      (error-message-string the-error))))))))
564
565 (defun elpher-get-gopher-node (renderer)
566   "Getter function for gopher nodes.
567 The RENDERER procedure is used to display the contents of the node
568 once they are retrieved from the gopher server."
569   (let* ((address (elpher-node-address elpher-current-node))
570          (content (elpher-get-cached-content address)))
571     (if (and content (funcall renderer nil))
572         (elpher-with-clean-buffer
573          (insert content)
574          (elpher-restore-pos))
575       (elpher-with-clean-buffer
576        (insert "LOADING... (use 'u' to cancel)"))
577       (elpher-get-selector address renderer))))
578
579 ;; Index rendering
580
581 (defun elpher-insert-index (string)
582   "Insert the index corresponding to STRING into the current buffer."
583   ;; Should be able to split directly on CRLF, but some non-conformant
584   ;; LF-only servers sadly exist, hence the following.
585   (let ((str-processed (elpher-preprocess-text-response string)))
586     (dolist (line (split-string str-processed "\n"))
587       (ignore-errors
588         (unless (= (length line) 0)
589           (let* ((type (elt line 0))
590                  (fields (split-string (substring line 1) "\t"))
591                  (display-string (elt fields 0))
592                  (selector (elt fields 1))
593                  (host (elt fields 2))
594                  (port (if (elt fields 3)
595                            (string-to-number (elt fields 3))
596                          nil))
597                  (address (elpher-make-gopher-address type selector host port)))
598             (elpher-insert-index-record display-string address)))))))
599
600 (defun elpher-insert-margin (&optional type-name)
601   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
602   (if type-name
603       (progn
604         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
605                         (concat
606                          (propertize "[" 'face 'elpher-margin-brackets)
607                          (propertize type-name 'face 'elpher-margin-key)
608                          (propertize "]" 'face 'elpher-margin-brackets))))
609         (insert " "))
610     (insert (make-string elpher-margin-width ?\s))))
611
612 (defun elpher-node-button-help (node)
613   "Return a string containing the help text for a button corresponding to NODE."
614   (let ((address (elpher-node-address node)))
615     (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
616                                           address
617                                         (elpher-address-to-url address)))))
618
619 (defun elpher-insert-index-record (display-string &optional address)
620   "Function to insert an index record into the current buffer.
621 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
622 If ADDRESS is not supplied or nil the record is rendered as an
623 'information' line."
624   (let* ((type (if address (elpher-address-type address) nil))
625          (type-map-entry (cdr (assoc type elpher-type-map))))
626     (if type-map-entry
627         (let* ((margin-code (elt type-map-entry 2))
628                (face (elt type-map-entry 3))
629                (node (elpher-make-node display-string address)))
630           (elpher-insert-margin margin-code)
631           (insert-text-button display-string
632                               'face face
633                               'elpher-node node
634                               'action #'elpher-click-link
635                               'follow-link t
636                               'help-echo (elpher-node-button-help node)))
637       (pcase type
638         ((or '(gopher ?i) 'nil) ;; Information
639          (elpher-insert-margin)
640          (let ((propertized-display-string
641                 (propertize display-string 'face 'elpher-info)))
642            (insert (if elpher-buttonify-urls-in-directories
643                        (elpher-buttonify-urls propertized-display-string)
644                      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 ((node (button-get button 'elpher-node)))
654     (elpher-visit-node node)))
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-node-address elpher-current-node)
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 buttniofy 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 ((node (elpher-make-node (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-node  node
682                             'action #'elpher-click-link
683                             'follow-link t
684                             'help-echo (elpher-node-button-help node)
685                             'face 'button)))
686     (buffer-string)))
687
688 (defun elpher-render-text (data &optional _mime-type-string)
689   "Render DATA as text.  MIME-TYPE-STRING is unused."
690   (elpher-with-clean-buffer
691    (if (not data)
692        t
693      (insert (elpher-buttonify-urls (elpher-preprocess-text-response data)))
694      (elpher-cache-content
695       (elpher-node-address elpher-current-node)
696       (buffer-string)))))
697
698 ;; Image retrieval
699
700 (defun elpher-render-image (data &optional _mime-type-string)
701   "Display DATA as image.  MIME-TYPE-STRING is unused."
702   (if (not data)
703       nil
704     (if (display-images-p)
705         (progn
706           (let ((image (create-image
707                         data
708                         nil t)))
709             (elpher-with-clean-buffer
710              (insert-image image)
711              (elpher-restore-pos))))
712       (elpher-render-download data))))
713
714 ;; Search retrieval and rendering
715
716 (defun elpher-get-gopher-query-node (renderer)
717   "Getter for gopher addresses requiring input.
718 The response is rendered using the rendering function RENDERER."
719    (let* ((address (elpher-node-address elpher-current-node))
720           (content (elpher-get-cached-content address))
721           (aborted t))
722     (if (and content (funcall renderer nil))
723         (elpher-with-clean-buffer
724          (insert content)
725          (elpher-restore-pos)
726          (message "Displaying cached search results.  Reload to perform a new search."))
727       (unwind-protect
728           (let* ((query-string (read-string "Query: "))
729                  (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
730                  (search-address (elpher-make-gopher-address ?1
731                                                              query-selector
732                                                              (elpher-address-host address)
733                                                              (elpher-address-port address)
734                                                              (equal (elpher-address-type address) "gophers"))))
735             (setq aborted nil)
736
737             (elpher-with-clean-buffer
738              (insert "LOADING RESULTS... (use 'u' to cancel)"))
739             (elpher-get-selector search-address renderer))
740         (if aborted
741             (elpher-visit-parent-node))))))
742  
743 ;; Raw server response rendering
744
745 (defun elpher-render-raw (data &optional mime-type-string)
746   "Display raw DATA in buffer.  MIME-TYPE-STRING is also displayed if provided."
747   (if (not data)
748       nil
749     (elpher-with-clean-buffer
750      (when mime-type-string
751        (insert "MIME type specified by server: '" mime-type-string "'\n"))
752      (insert data)
753      (goto-char (point-min)))
754     (message "Displaying raw server response.  Reload or redraw to return to standard view.")))
755
756 ;; File save "rendering"
757
758 (defun elpher-render-download (data &optional _mime-type-string)
759   "Save DATA to file.  MIME-TYPE-STRING is unused."
760   (if (not data)
761       nil
762     (let* ((address (elpher-node-address elpher-current-node))
763            (selector (elpher-gopher-address-selector address)))
764       (elpher-visit-parent-node) ; Do first in case of non-local exits.
765       (let* ((filename-proposal (file-name-nondirectory selector))
766              (filename (read-file-name "Download complete. Save file as: "
767                                        nil nil nil
768                                        (if (> (length filename-proposal) 0)
769                                            filename-proposal
770                                          "download.file"))))
771         (let ((coding-system-for-write 'binary))
772           (with-temp-file filename
773             (insert data)))
774         (message (format "Saved to file %s." filename))))))
775
776 ;; HTML rendering
777
778 (defun elpher-render-html (data &optional _mime-type-string)
779   "Render DATA as HTML using shr.  MIME-TYPE-STRING is unused."
780   (elpher-with-clean-buffer
781    (if (not data)
782        t
783      (let ((dom (with-temp-buffer
784                   (insert data)
785                   (libxml-parse-html-region (point-min) (point-max)))))
786        (shr-insert-document dom)))))
787
788 ;; Gemini node retrieval
789
790 (defvar elpher-gemini-redirect-chain)
791
792 (defun elpher-get-gemini-response (address renderer &optional force-ipv4)
793   "Retrieve gemini ADDRESS, then render using RENDERER.
794 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
795 to ADDRESS."
796   (if (not (gnutls-available-p))
797       (error "Cannot establish gemini connection: GnuTLS not available")
798     (unless (< (elpher-address-port address) 65536)
799       (error "Cannot establish gemini connection: port number > 65536"))
800     (condition-case the-error
801         (let* ((kill-buffer-query-functions nil)
802                (network-security-level 'medium)
803                (port (elpher-address-port address))
804                (host (elpher-address-host address))
805                (response-string "")
806                (proc (open-network-stream "elpher-process"
807                                           nil
808                                           (if force-ipv4 (dns-query host) host)
809                                           (if (> port 0) port 1965)
810                                           :type 'tls
811                                           :nowait t))
812                (timer (run-at-time elpher-connection-timeout nil
813                                    (lambda ()
814                                      (elpher-process-cleanup)
815                                      (unless force-ipv4
816                                         ; Try again with IPv4
817                                        (message "Connection timed out.  Retrying with IPv4.")
818                                        (elpher-get-gemini-response address renderer t))))))
819           (setq elpher-network-timer timer)
820           (set-process-coding-system proc 'binary)
821           (set-process-filter proc
822                               (lambda (_proc string)
823                                 (cancel-timer timer)
824                                 (setq response-string
825                                       (concat response-string string))))
826           (set-process-sentinel proc
827                                 (lambda (proc event)
828                                   (condition-case the-error
829                                       (cond
830                                        ((string-prefix-p "open" event)    ; request URL
831                                         (let ((inhibit-eol-conversion t))
832                                           (process-send-string
833                                            proc
834                                            (concat (elpher-address-to-url address)
835                                                    "\r\n"))))
836                                        ((string-prefix-p "deleted" event)) ; do nothing
837                                        ((and (string-empty-p response-string)
838                                              (not force-ipv4))
839                                         ; Try again with IPv4
840                                         (message "Connection failed. Retrying with IPv4.")
841                                         (cancel-timer timer)
842                                         (elpher-get-gemini-response address renderer t))
843                                        (t 
844                                         (funcall #'elpher-process-gemini-response
845                                                  response-string
846                                                  renderer)
847                                         (elpher-restore-pos)))
848                                     (error the-error
849                                            (elpher-network-error address the-error))))))
850       (error
851        (error "Error initiating connection to server")))))
852
853 (defun elpher-parse-gemini-response (response)
854   "Parse the RESPONSE string and return a list of components
855 The list is of the form (code meta body). A response of nil implies
856 that the response was malformed."
857   (let ((header-end-idx (string-match "\r\n" response)))
858     (if header-end-idx
859         (let ((header (string-trim (substring response 0 header-end-idx)))
860               (body (substring response (+ header-end-idx 2))))
861           (if (>= (length header) 2)
862               (let ((code (substring header 0 2))
863                     (meta (string-trim (substring header 2))))
864                 (list code meta body))
865             (error "Malformed response: No response status found in header %s" header)))
866       (error "Malformed response: No CRLF-delimited header found"))))
867
868 (defun elpher-process-gemini-response (response-string renderer)
869   "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
870   (let ((response-components (elpher-parse-gemini-response response-string)))
871     (let ((response-code (elt response-components 0))
872           (response-meta (elt response-components 1))
873           (response-body (elt response-components 2)))
874       (pcase (elt response-code 0)
875         (?1 ; Input required
876          (elpher-with-clean-buffer
877           (insert "Gemini server is requesting input."))
878          (let* ((query-string (read-string (concat response-meta ": ")))
879                 (url (elpher-address-to-url (elpher-node-address elpher-current-node)))
880                 (query-address (elpher-address-from-url (concat url "?" query-string))))
881            (elpher-get-gemini-response query-address renderer)))
882         (?2 ; Normal response
883          (funcall renderer response-body response-meta))
884         (?3 ; Redirect
885          (message "Following redirect to %s" response-meta)
886          (if (>= (length elpher-gemini-redirect-chain) 5)
887              (error "More than 5 consecutive redirects followed"))
888          (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
889            (if (member redirect-address elpher-gemini-redirect-chain)
890                (error "Redirect loop detected"))
891            (if (not (string= (elpher-address-protocol redirect-address)
892                              "gemini"))
893                (error "Server tried to automatically redirect to non-gemini URL: %s"
894                       response-meta))
895            (add-to-list 'elpher-gemini-redirect-chain redirect-address)
896            (elpher-get-gemini-response redirect-address renderer)))
897         (?4 ; Temporary failure
898          (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
899                 response-code response-meta))
900         (?5 ; Permanent failure
901          (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
902                 response-code response-meta))
903         (?6 ; Client certificate required
904          (error "Gemini server requires client certificate (unsupported at this time)"))
905         (_other
906          (error "Gemini server response unknown: %s %s"
907                 response-code response-meta))))))
908
909 (defun elpher-get-gemini-node (renderer)
910   "Getter which retrieves and renders a Gemini node and renders it using RENDERER."
911   (let* ((address (elpher-node-address elpher-current-node))
912          (content (elpher-get-cached-content address)))
913     (condition-case the-error
914         (if (and content (funcall renderer nil))
915             (elpher-with-clean-buffer
916               (insert content)
917               (elpher-restore-pos))
918           (elpher-with-clean-buffer
919            (insert "LOADING GEMINI... (use 'u' to cancel)"))
920           (setq elpher-gemini-redirect-chain nil)
921           (elpher-get-gemini-response address renderer))
922       (error
923        (elpher-network-error address the-error)))))
924
925
926 (defun elpher-render-gemini (body &optional mime-type-string)
927   "Render gemini response BODY with rendering MIME-TYPE-STRING."
928   (if (not body)
929       t
930     (let* ((mime-type-string* (if (or (not mime-type-string)
931                                       (string-empty-p mime-type-string))
932                                   "text/gemini; charset=utf-8"
933                                 mime-type-string))
934            (mime-type-split (split-string mime-type-string* ";" t))
935            (mime-type (string-trim (car mime-type-split)))
936            (parameters (mapcar (lambda (s)
937                                  (let ((key-val (split-string s "=")))
938                                    (list (downcase (string-trim (car key-val)))
939                                          (downcase (string-trim (cadr key-val))))))
940                                (cdr mime-type-split))))
941       (when (string-prefix-p "text/" mime-type)
942         (setq body (decode-coding-string
943                     body
944                     (if (assoc "charset" parameters)
945                         (intern (cadr (assoc "charset" parameters)))
946                       'utf-8)))
947         (setq body (replace-regexp-in-string "\r" "" body)))
948       (pcase mime-type
949         ((or "text/gemini" "")
950          (elpher-render-gemini-map body parameters))
951         ("text/html"
952          (elpher-render-html body))
953         ((pred (string-prefix-p "text/"))
954          (elpher-render-gemini-plain-text body parameters))
955         ((pred (string-prefix-p "image/"))
956          (elpher-render-image body))
957         (_other
958          (error "Unsupported MIME type %S" mime-type))))))
959
960 (defun elpher-gemini-get-link-url (line)
961   "Extract the url portion of LINE, a gemini map file link line."
962   (string-trim (elt (split-string (substring line 2)) 0)))
963
964 (defun elpher-gemini-get-link-display-string (line)
965   "Extract the display string portion of LINE, a gemini map file link line."
966   (let* ((rest (string-trim (elt (split-string line "=>") 1)))
967          (idx (string-match "[ \t]" rest)))
968     (if idx
969         (string-trim (substring rest (+ idx 1)))
970       "")))
971
972 (defun elpher-collapse-dot-sequences (filename)
973   "Collapse dot sequences in FILENAME.
974 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
975   (let* ((path (split-string filename "/"))
976          (path-reversed-normalized
977           (seq-reduce (lambda (a b)
978                         (cond ((and a (equal b "..") (cdr a)))
979                               ((and (not a) (equal b "..")) a) ;leading .. are dropped
980                               ((equal b ".") a)
981                               (t (cons b a))))
982                       path nil)))
983     (string-join (reverse path-reversed-normalized) "/")))
984
985 (defun elpher-address-from-gemini-url (url)
986   "Extract address from URL with defaults as per gemini map files."
987   (let ((address (url-generic-parse-url url)))
988     (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
989       (setf (url-fullness address) t)
990       (if (url-host address) ;if there is an explicit host, filenames are absolute
991           (if (string-empty-p (url-filename address))
992               (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
993         (setf (url-host address) (url-host (elpher-node-address elpher-current-node)))
994         (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
995           (setf (url-filename address)
996                 (concat (file-name-directory
997                          (url-filename (elpher-node-address elpher-current-node)))
998                         (url-filename address)))))
999       (unless (url-type address)
1000         (setf (url-type address) "gemini"))
1001       (if (equal (url-type address) "gemini")
1002           (setf (url-filename address)
1003                 (elpher-collapse-dot-sequences (url-filename address)))))
1004     address))
1005
1006 (defun elpher-render-gemini-map (data _parameters)
1007   "Render DATA as a gemini map file, PARAMETERS is currently unused."
1008   (elpher-with-clean-buffer
1009    (dolist (line (split-string data "\n"))
1010      (if (string-prefix-p "=>" line)
1011          (let* ((url (elpher-gemini-get-link-url line))
1012                 (display-string (elpher-gemini-get-link-display-string line))
1013                 (address (elpher-address-from-gemini-url url)))
1014            (if (> (length display-string) 0)
1015                (elpher-insert-index-record display-string address)
1016              (elpher-insert-index-record url address)))
1017        (elpher-insert-index-record line)))
1018    (elpher-cache-content
1019     (elpher-node-address elpher-current-node)
1020     (buffer-string))))
1021
1022 (defun elpher-render-gemini-plain-text (data _parameters)
1023   "Render DATA as plain text file.  PARAMETERS is currently unused."
1024   (elpher-with-clean-buffer
1025    (insert (elpher-buttonify-urls data))
1026    (elpher-cache-content
1027     (elpher-node-address elpher-current-node)
1028     (buffer-string))))
1029
1030 ;; Other URL node opening
1031
1032 (defun elpher-get-other-url-node (renderer)
1033   "Getter which attempts to open the URL specified by the current node (RENDERER must be nil)."
1034   (when renderer
1035     (elpher-visit-parent-node)
1036     (error "Command not supported for general URLs"))
1037   (let* ((address (elpher-node-address elpher-current-node))
1038          (url (elpher-address-to-url address)))
1039     (progn
1040       (elpher-visit-parent-node) ; Do first in case of non-local exits.
1041       (message "Opening URL...")
1042       (if elpher-open-urls-with-eww
1043           (browse-web url)
1044         (browse-url url)))))
1045
1046 ;; Telnet node connection
1047
1048 (defun elpher-get-telnet-node (renderer)
1049   "Opens a telnet connection to the current node address (RENDERER must be nil)."
1050   (when renderer
1051     (elpher-visit-parent-node)
1052     (error "Command not supported for telnet URLs"))
1053   (let* ((address (elpher-node-address elpher-current-node))
1054          (host (elpher-address-host address))
1055          (port (elpher-address-port address)))
1056     (elpher-visit-parent-node)
1057     (if (> port 0)
1058         (telnet host port)
1059       (telnet host))))
1060
1061 ;; Start page node retrieval
1062
1063 (defun elpher-get-start-node (renderer)
1064   "Getter which displays the start page (RENDERER must be nil)."
1065   (when renderer
1066     (elpher-visit-parent-node)
1067     (error "Command not supported for start page"))
1068   (elpher-with-clean-buffer
1069    (insert "     --------------------------------------------\n"
1070            "                Elpher Gopher Client             \n"
1071            "                   version " elpher-version "\n"
1072            "     --------------------------------------------\n"
1073            "\n"
1074            "Default bindings:\n"
1075            "\n"
1076            " - TAB/Shift-TAB: next/prev item on current page\n"
1077            " - RET/mouse-1: open item under cursor\n"
1078            " - m: select an item on current page by name (autocompletes)\n"
1079            " - u/mouse-3: return to previous page\n"
1080            " - o/O: visit different selector or the root menu of the current server\n"
1081            " - g: go to a particular gopher address\n"
1082            " - d/D: download item under cursor or current page\n"
1083            " - i/I: info on item under cursor or current page\n"
1084            " - c/C: copy URL representation of item under cursor or current page\n"
1085            " - a/A: bookmark the item under cursor or current page\n"
1086            " - x/X: remove bookmark for item under cursor or current page\n"
1087            " - B: visit the bookmarks page\n"
1088            " - r: redraw current page (using cached contents if available)\n"
1089            " - R: reload current page (regenerates cache)\n"
1090            " - S: set character coding system for gopher (default is to autodetect)\n"
1091            " - T: toggle TLS gopher mode\n"
1092            " - .: display the raw server response for the current page\n"
1093            "\n"
1094            "Start your exploration of gopher space:\n")
1095    (elpher-insert-index-record "Floodgap Systems Gopher Server"
1096                                (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1097    (insert "\n"
1098            "Alternatively, select the following item and enter some search terms:\n")
1099    (elpher-insert-index-record "Veronica-2 Gopher Search Engine"
1100                                (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1101    (insert "\n"
1102            "This page contains your bookmarked sites (also visit with B):\n")
1103    (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1104    (insert "\n"
1105            "** Refer to the ")
1106    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1107      (insert-text-button "Elpher info manual"
1108                          'face 'link
1109                          'action (lambda (_)
1110                                    (interactive)
1111                                    (info "(elpher)"))
1112                          'follow-link t
1113                          'help-echo help-string))
1114    (insert " for the full documentation. **\n")
1115    (insert (propertize
1116             (concat "  (This should be available if you have installed Elpher using\n"
1117                     "   MELPA. Otherwise you will have to install the manual yourself.)")
1118             'face 'shadow))
1119    (elpher-restore-pos)))
1120
1121 ;; Bookmarks page node retrieval
1122
1123 (defun elpher-get-bookmarks-node (renderer)
1124   "Getter to load and display the current bookmark list (RENDERER must be nil)."
1125   (when renderer
1126     (elpher-visit-parent-node)
1127     (error "Command not supported for bookmarks page"))
1128   (elpher-with-clean-buffer
1129    (insert "---- Bookmark list ----\n\n")
1130    (let ((bookmarks (elpher-load-bookmarks)))
1131      (if bookmarks
1132          (dolist (bookmark bookmarks)
1133            (let ((display-string (elpher-bookmark-display-string bookmark))
1134                  (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1135              (elpher-insert-index-record display-string address)))
1136        (insert "No bookmarks found.\n")))
1137    (insert "\n-----------------------\n"
1138            "\n"
1139            "- u: return to previous page\n"
1140            "- x: delete selected bookmark\n"
1141            "- a: rename selected bookmark\n"
1142            "\n"
1143            "Bookmarks are stored in the file ")
1144    (let ((filename (locate-user-emacs-file "elpher-bookmarks"))
1145          (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1146      (insert-text-button filename
1147                          'face 'link
1148                          'action (lambda (_)
1149                                    (interactive)
1150                                    (find-file filename))
1151                          'follow-link t
1152                          'help-echo help-string))
1153    (insert "\n")
1154    (elpher-restore-pos)))
1155   
1156
1157 ;;; Bookmarks
1158 ;;
1159
1160 (defun elpher-make-bookmark (display-string url)
1161   "Make an elpher bookmark.
1162 DISPLAY-STRING determines how the bookmark will appear in the
1163 bookmark list, while URL is the url of the entry."
1164   (list display-string url))
1165   
1166 (defun elpher-bookmark-display-string (bookmark)
1167   "Get the display string of BOOKMARK."
1168   (elt bookmark 0))
1169
1170 (defun elpher-set-bookmark-display-string (bookmark display-string)
1171   "Set the display string of BOOKMARK to DISPLAY-STRING."
1172   (setcar bookmark display-string))
1173
1174 (defun elpher-bookmark-url (bookmark)
1175   "Get the address for BOOKMARK."
1176   (elt bookmark 1))
1177
1178 (defun elpher-save-bookmarks (bookmarks)
1179   "Record the bookmark list BOOKMARKS to the user's bookmark file.
1180 Beware that this completely replaces the existing contents of the file."
1181   (with-temp-file (locate-user-emacs-file "elpher-bookmarks")
1182     (erase-buffer)
1183     (insert "; Elpher bookmarks file\n\n"
1184             "; Bookmarks are stored as a list of (label URL) items.\n"
1185             "; Feel free to edit by hand, but take care to ensure\n"
1186             "; the list structure remains intact.\n\n")
1187     (pp bookmarks (current-buffer))))
1188
1189 (defun elpher-load-bookmarks ()
1190   "Get the list of bookmarks from the users's bookmark file."
1191   (let ((bookmarks
1192          (with-temp-buffer
1193            (ignore-errors
1194              (insert-file-contents (locate-user-emacs-file "elpher-bookmarks"))
1195              (goto-char (point-min))
1196              (read (current-buffer))))))
1197     (if (and bookmarks (listp (cadar bookmarks)))
1198         (progn
1199           (message "Reading old bookmark file. (Will be updated on write.)")
1200           (mapcar (lambda (old-bm)
1201                     (list (car old-bm)
1202                           (elpher-address-to-url (apply #'elpher-make-gopher-address
1203                                                         (cadr old-bm)))))
1204                   bookmarks))
1205       bookmarks)))
1206
1207 (defun elpher-add-address-bookmark (address display-string)
1208   "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1209 If ADDRESS is already bookmarked, update the label only."
1210   (let ((bookmarks (elpher-load-bookmarks))
1211         (url (elpher-address-to-url address)))
1212     (let ((existing-bookmark (rassoc (list url) bookmarks)))
1213       (if existing-bookmark
1214           (elpher-set-bookmark-display-string existing-bookmark display-string)
1215         (push (elpher-make-bookmark display-string url) bookmarks)))
1216     (elpher-save-bookmarks bookmarks)))
1217
1218 (defun elpher-remove-address-bookmark (address)
1219   "Remove any bookmark to ADDRESS."
1220   (let ((url (elpher-address-to-url address)))
1221     (elpher-save-bookmarks
1222      (seq-filter (lambda (bookmark)
1223                    (not (equal (elpher-bookmark-url bookmark) url)))
1224                  (elpher-load-bookmarks)))))
1225
1226 ;;; Interactive procedures
1227 ;;
1228
1229 (defun elpher-next-link ()
1230   "Move point to the next link on the current page."
1231   (interactive)
1232   (forward-button 1))
1233
1234 (defun elpher-prev-link ()
1235   "Move point to the previous link on the current page."
1236   (interactive)
1237   (backward-button 1))
1238
1239 (defun elpher-follow-current-link ()
1240   "Open the link or url at point."
1241   (interactive)
1242   (push-button))
1243
1244 (defun elpher-go ()
1245   "Go to a particular gopher site read from the minibuffer."
1246   (interactive)
1247   (let ((node
1248          (let ((host-or-url (read-string "Gopher or Gemini URL: ")))
1249            (elpher-make-node host-or-url
1250                              (elpher-address-from-url host-or-url)))))
1251     (switch-to-buffer "*elpher*")
1252     (elpher-visit-node node)))
1253
1254 (defun elpher-go-current ()
1255   "Go to a particular site read from the minibuffer, initialized with the current URL."
1256   (interactive)
1257   (let ((address (elpher-node-address elpher-current-node)))
1258     (if (elpher-address-special-p address)
1259         (error "Command invalid for this page")
1260       (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1261         (elpher-visit-node (elpher-make-node url (elpher-address-from-url url)))))))
1262
1263 (defun elpher-redraw ()
1264   "Redraw current page."
1265   (interactive)
1266   (if elpher-current-node
1267       (elpher-visit-node elpher-current-node)
1268     (message "No current site.")))
1269
1270 (defun elpher-reload ()
1271   "Reload current page."
1272   (interactive)
1273   (if elpher-current-node
1274       (elpher-reload-current-node)
1275     (message "No current site.")))
1276
1277 (defun elpher-toggle-tls ()
1278   "Toggle TLS encryption mode for gopher."
1279   (interactive)
1280   (setq elpher-use-tls (not elpher-use-tls))
1281   (if elpher-use-tls
1282       (if (gnutls-available-p)
1283           (message "TLS gopher mode enabled.  (Will not affect current page until reload.)")
1284         (setq elpher-use-tls nil)
1285         (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1286     (message "TLS gopher mode disabled.  (Will not affect current page until reload.)")))
1287
1288 (defun elpher-view-raw ()
1289   "View raw server response for current page."
1290   (interactive)
1291   (if elpher-current-node
1292       (if (elpher-address-special-p (elpher-node-address elpher-current-node))
1293           (error "This page was not generated by a server")
1294         (elpher-visit-node elpher-current-node
1295                            #'elpher-render-raw))
1296     (message "No current site.")))
1297
1298 (defun elpher-back ()
1299   "Go to previous site."
1300   (interactive)
1301   (if (elpher-node-parent elpher-current-node)
1302       (elpher-visit-parent-node)
1303     (error "No previous site")))
1304
1305 (defun elpher-download ()
1306   "Download the link at point."
1307   (interactive)
1308   (let ((button (button-at (point))))
1309     (if button
1310         (let ((node (button-get button 'elpher-node)))
1311           (if (elpher-address-special-p (elpher-node-address node))
1312               (error "Cannot download %s"
1313                      (elpher-node-display-string node))
1314             (elpher-visit-node (button-get button 'elpher-node)
1315                                #'elpher-render-download)))
1316       (error "No link selected"))))
1317
1318 (defun elpher-download-current ()
1319   "Download the current page."
1320   (interactive)
1321   (if (elpher-address-special-p (elpher-node-address elpher-current-node))
1322       (error "Cannot download %s"
1323              (elpher-node-display-string elpher-current-node))
1324     (elpher-visit-node (elpher-make-node
1325                         (elpher-node-display-string elpher-current-node)
1326                         (elpher-node-address elpher-current-node)
1327                         elpher-current-node)
1328                        #'elpher-render-download
1329                        t)))
1330
1331 (defun elpher-build-link-map ()
1332   "Build alist mapping link names to destination nodes in current buffer."
1333   (let ((link-map nil)
1334         (b (next-button (point-min) t)))
1335     (while b
1336       (push (cons (button-label b) b) link-map)
1337       (setq b (next-button (button-start b))))
1338     link-map))
1339
1340 (defun elpher-jump ()
1341   "Select a directory entry by name.  Similar to the info browser (m)enu command."
1342   (interactive)
1343   (let* ((link-map (elpher-build-link-map)))
1344     (if link-map
1345         (let ((key (let ((completion-ignore-case t))
1346                      (completing-read "Directory item/link: "
1347                                       link-map nil t))))
1348           (if (and key (> (length key) 0))
1349               (let ((b (cdr (assoc key link-map))))
1350                 (goto-char (button-start b))
1351                 (button-activate b)))))))
1352
1353 (defun elpher-root-dir ()
1354   "Visit root of current server."
1355   (interactive)
1356   (let ((address (elpher-node-address elpher-current-node)))
1357     (if (not (elpher-address-special-p address))
1358         (if (or (member (url-filename address) '("/" ""))
1359                 (and (elpher-address-gopher-p address)
1360                      (= (length (elpher-gopher-address-selector address)) 0)))
1361             (error "Already at root directory of current server")
1362           (let ((address-copy (elpher-address-from-url
1363                                (elpher-address-to-url address))))
1364             (setf (url-filename address-copy) "")
1365             (elpher-visit-node
1366              (elpher-make-node (elpher-address-to-url address-copy)
1367                                address-copy))))
1368       (error "Command invalid for %s" (elpher-node-display-string elpher-current-node)))))
1369
1370 (defun elpher-bookmarks-current-p ()
1371   "Return non-nil if current node is a bookmarks page."
1372   (equal (elpher-address-type (elpher-node-address elpher-current-node))
1373          '(special bookmarks)))
1374
1375 (defun elpher-reload-bookmarks ()
1376   "Reload bookmarks if current node is a bookmarks page."
1377   (if (elpher-bookmarks-current-p)
1378       (elpher-reload-current-node)))
1379
1380 (defun elpher-bookmark-current ()
1381   "Bookmark the current node."
1382   (interactive)
1383   (let ((address (elpher-node-address elpher-current-node))
1384         (display-string (elpher-node-display-string elpher-current-node)))
1385     (if (not (elpher-address-special-p address))
1386         (let ((bookmark-display-string (read-string "Bookmark display string: "
1387                                                     display-string)))
1388           (elpher-add-address-bookmark address bookmark-display-string)
1389           (message "Bookmark added."))
1390       (error "Cannot bookmark %s" display-string))))
1391
1392 (defun elpher-bookmark-link ()
1393   "Bookmark the link at point."
1394   (interactive)
1395   (let ((button (button-at (point))))
1396     (if button
1397         (let* ((node (button-get button 'elpher-node))
1398                (address (elpher-node-address node))
1399                (display-string (elpher-node-display-string node)))
1400           (if (not (elpher-address-special-p address))
1401               (let ((bookmark-display-string (read-string "Bookmark display string: "
1402                                                           display-string)))
1403                 (elpher-add-address-bookmark address bookmark-display-string)
1404                 (elpher-reload-bookmarks)
1405                 (message "Bookmark added."))
1406             (error "Cannot bookmark %s" display-string)))
1407       (error "No link selected"))))
1408
1409 (defun elpher-unbookmark-current ()
1410   "Remove bookmark for the current node."
1411   (interactive)
1412   (let ((address (elpher-node-address elpher-current-node)))
1413     (unless (elpher-address-special-p address)
1414       (elpher-remove-address-bookmark address)
1415       (message "Bookmark removed."))))
1416
1417 (defun elpher-unbookmark-link ()
1418   "Remove bookmark for the link at point."
1419   (interactive)
1420   (let ((button (button-at (point))))
1421     (if button
1422         (let ((node (button-get button 'elpher-node)))
1423           (elpher-remove-address-bookmark (elpher-node-address node))
1424           (elpher-reload-bookmarks)
1425           (message "Bookmark removed."))
1426       (error "No link selected"))))
1427
1428 (defun elpher-bookmarks ()
1429   "Visit bookmarks page."
1430   (interactive)
1431   (switch-to-buffer "*elpher*")
1432   (elpher-visit-node
1433    (elpher-make-node "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
1434
1435 (defun elpher-info-node (node)
1436   "Display information on NODE."
1437   (let ((display-string (elpher-node-display-string node))
1438         (address (elpher-node-address node)))
1439     (if (elpher-address-special-p address)
1440         (message "Special page: %s" display-string)
1441       (message "%s" (elpher-address-to-url address)))))
1442
1443 (defun elpher-info-link ()
1444   "Display information on node corresponding to link at point."
1445   (interactive)
1446   (let ((button (button-at (point))))
1447     (if button
1448         (elpher-info-node (button-get button 'elpher-node))
1449       (error "No item selected"))))
1450   
1451 (defun elpher-info-current ()
1452   "Display information on current node."
1453   (interactive)
1454   (elpher-info-node elpher-current-node))
1455
1456 (defun elpher-copy-node-url (node)
1457   "Copy URL representation of address of NODE to `kill-ring'."
1458   (let ((address (elpher-node-address node)))
1459     (if (elpher-address-special-p address)
1460         (error (format "Cannot represent %s as URL" (elpher-node-display-string node)))
1461       (let ((url (elpher-address-to-url address)))
1462         (message "Copied \"%s\" to kill-ring/clipboard." url)
1463         (kill-new url)))))
1464
1465 (defun elpher-copy-link-url ()
1466   "Copy URL of item at point to `kill-ring'."
1467   (interactive)
1468   (let ((button (button-at (point))))
1469     (if button
1470         (elpher-copy-node-url (button-get button 'elpher-node))
1471       (error "No item selected"))))
1472
1473 (defun elpher-copy-current-url ()
1474   "Copy URL of current node to `kill-ring'."
1475   (interactive)
1476   (elpher-copy-node-url elpher-current-node))
1477
1478 (defun elpher-set-gopher-coding-system ()
1479   "Specify an explicit character coding system for gopher selectors."
1480   (interactive)
1481   (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
1482     (setq elpher-user-coding-system system)
1483     (if system
1484         (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
1485       (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
1486
1487
1488 ;;; Mode and keymap
1489 ;;
1490
1491 (defvar elpher-mode-map
1492   (let ((map (make-sparse-keymap)))
1493     (define-key map (kbd "TAB") 'elpher-next-link)
1494     (define-key map (kbd "<backtab>") 'elpher-prev-link)
1495     (define-key map (kbd "u") 'elpher-back)
1496     (define-key map [mouse-3] 'elpher-back)
1497     (define-key map (kbd "O") 'elpher-root-dir)
1498     (define-key map (kbd "g") 'elpher-go)
1499     (define-key map (kbd "o") 'elpher-go-current)
1500     (define-key map (kbd "r") 'elpher-redraw)
1501     (define-key map (kbd "R") 'elpher-reload)
1502     (define-key map (kbd "T") 'elpher-toggle-tls)
1503     (define-key map (kbd ".") 'elpher-view-raw)
1504     (define-key map (kbd "d") 'elpher-download)
1505     (define-key map (kbd "D") 'elpher-download-current)
1506     (define-key map (kbd "m") 'elpher-jump)
1507     (define-key map (kbd "i") 'elpher-info-link)
1508     (define-key map (kbd "I") 'elpher-info-current)
1509     (define-key map (kbd "c") 'elpher-copy-link-url)
1510     (define-key map (kbd "C") 'elpher-copy-current-url)
1511     (define-key map (kbd "a") 'elpher-bookmark-link)
1512     (define-key map (kbd "A") 'elpher-bookmark-current)
1513     (define-key map (kbd "x") 'elpher-unbookmark-link)
1514     (define-key map (kbd "X") 'elpher-unbookmark-current)
1515     (define-key map (kbd "B") 'elpher-bookmarks)
1516     (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
1517     (when (fboundp 'evil-define-key*)
1518       (evil-define-key* 'motion map
1519         (kbd "TAB") 'elpher-next-link
1520         (kbd "C-") 'elpher-follow-current-link
1521         (kbd "C-t") 'elpher-back
1522         (kbd "u") 'elpher-back
1523         [mouse-3] 'elpher-back
1524         (kbd "g") 'elpher-go
1525         (kbd "o") 'elpher-go-current
1526         (kbd "r") 'elpher-redraw
1527         (kbd "R") 'elpher-reload
1528         (kbd "T") 'elpher-toggle-tls
1529         (kbd ".") 'elpher-view-raw
1530         (kbd "d") 'elpher-download
1531         (kbd "D") 'elpher-download-current
1532         (kbd "m") 'elpher-jump
1533         (kbd "i") 'elpher-info-link
1534         (kbd "I") 'elpher-info-current
1535         (kbd "c") 'elpher-copy-link-url
1536         (kbd "C") 'elpher-copy-current-url
1537         (kbd "a") 'elpher-bookmark-link
1538         (kbd "A") 'elpher-bookmark-current
1539         (kbd "x") 'elpher-unbookmark-link
1540         (kbd "X") 'elpher-unbookmark-current
1541         (kbd "B") 'elpher-bookmarks
1542         (kbd "S") 'elpher-set-gopher-coding-system))
1543     map)
1544   "Keymap for gopher client.")
1545
1546 (define-derived-mode elpher-mode special-mode "elpher"
1547   "Major mode for elpher, an elisp gopher client.
1548
1549 This mode is automatically enabled by the interactive
1550 functions which initialize the gopher client, namely
1551 `elpher', `elpher-go' and `elpher-bookmarks'.")
1552
1553 (when (fboundp 'evil-set-initial-state)
1554   (evil-set-initial-state 'elpher-mode 'motion))
1555
1556
1557 ;;; Main start procedure
1558 ;;
1559
1560 ;;;###autoload
1561 (defun elpher ()
1562   "Start elpher with default landing page."
1563   (interactive)
1564   (if (get-buffer "*elpher*")
1565       (switch-to-buffer "*elpher*")
1566     (switch-to-buffer "*elpher*")
1567     (setq elpher-current-node nil)
1568     (let ((start-node (elpher-make-node "Elpher Start Page"
1569                                         (elpher-make-special-address 'start))))
1570       (elpher-visit-node start-node)))
1571   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
1572
1573 ;;; elpher.el ends here