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