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