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