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