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