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