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