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