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