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