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