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