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