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