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