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