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