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