Now h-type entries are nodes the same as everything else.
[elpher.git] / elpher.el
1 ;;; elpher.el --- Full-featured 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.1.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 full-featured gopher client for GNU Emacs.
30 ;; It supports:
31
32 ;; - intuitive keyboard and mouse-driven browsing,
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
39 ;; Visited pages are stored as a hierarchy rather than a linear history,
40 ;; meaning that navigation between these pages is quick and easy.
41
42 ;; To launch Elpher, simply use 'M-x elpher'.  This will open a start
43 ;; page containing information on key bindings and suggested starting
44 ;; points for your gopher exploration.
45
46 ;; Faces, caching options and start page can be configured via
47 ;; the Elpher customization group in Applications.
48
49 ;;; Code:
50
51 (provide 'elpher)
52 (require 'seq)
53 (require 'pp)
54
55 ;;; Global constants
56 ;;
57
58 (defconst elpher-version "1.1.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 directory entry on current page\tfake\tfake\t1"
76          "i - RET/mouse-1: open directory entry under cursor\tfake\tfake\t1"
77          "i - m: select a directory entry by name (autocompletes)\tfake\tfake\t1"
78          "i - u: return to parent directory entry\tfake\tfake\t1"
79          "i - O: visit the root directory of the current server\tfake\tfake\t1"
80          "i - g: go to a particular page\tfake\tfake\t1"
81          "i - r: redraw current page (using cached contents if available)\tfake\tfake\t1"
82          "i - R: reload current page (regenerates cache)\tfake\tfake\t1"
83          "i - d: download directory entry under cursor\tfake\tfake\t1"
84          "i - w: display the raw server response for the current page\tfake\tfake\t1"
85          "i\tfake\tfake\t1"
86          "iPlaces to start exploring Gopherspace:\tfake\tfake\t1"
87          "i\tfake\tfake\t1"
88          "1Floodgap Systems Gopher Server\t\tgopher.floodgap.com\t70"
89          "i\tfake\tfake\t1"
90          "iAlternatively, select the following item and enter some\tfake\tfake\t1"
91          "isearch terms:\tfake\tfake\t1"
92          "i\tfake\tfake\t1"
93          "7Veronica-2 Gopher Search Engine\t/v2/vs\tgopher.floodgap.com\t70"
94          ".\r\n")
95    "\r\n")
96   "Source for elpher start page.")
97
98 (defconst elpher-type-map
99   '((?0 elpher-get-text-node "T" elpher-text)
100     (?1 elpher-get-index-node "/" elpher-index)
101     (?g elpher-get-image-node "im" elpher-image)
102     (?p elpher-get-image-node "im" elpher-image)
103     (?I elpher-get-image-node "im" elpher-image)
104     (?4 elpher-get-node-download "B" elpher-binary)
105     (?5 elpher-get-node-download "B" elpher-binary)
106     (?9 elpher-get-node-download "B" elpher-binary)
107     (?7 elpher-get-search-node "?" elpher-search)
108     (?h elpher-get-url "W" elpher-url))
109   "Association list from types to getters, margin codes and index faces.")
110
111
112 ;;; Customization group
113 ;;
114
115 (defgroup elpher nil
116   "A gopher client."
117   :group 'applications)
118
119 ;; Face customizations
120
121 (defface elpher-index
122   '((t :inherit org-drawer))
123   "Face used for directory type directory records.")
124
125 (defface elpher-text
126   '((t :inherit org-tag))
127   "Face used for text type directory records.")
128
129 (defface elpher-info
130   '((t :inherit org-default))
131   "Face used for info type directory records.")
132
133 (defface elpher-image
134   '((t :inherit org-level-4))
135   "Face used for image type directory records.")
136
137 (defface elpher-search
138   '((t :inherit org-level-5))
139   "Face used for search type directory records.")
140
141 (defface elpher-url
142   '((t :inherit org-level-6))
143   "Face used for url type directory records.")
144
145 (defface elpher-binary
146   '((t :inherit org-level-7))
147   "Face used for binary type directory records.")
148
149 (defface elpher-unknown
150   '((t :inherit org-warning))
151   "Face used for directory records with unknown/unsupported types.")
152
153 (defface elpher-margin-key
154   '((t :inherit org-tag))
155   "Face used for directory margin key.")
156
157 (defface elpher-margin-brackets
158   '((t :inherit org-special-keyword))
159   "Face used for brackets around directory margin key.")
160
161 ;; Other customizations
162
163 (defcustom elpher-open-urls-with-eww nil
164   "If non-nil, open URL selectors using eww.
165 Otherwise, use the system browser via the BROWSE-URL function."
166   :type '(boolean))
167
168 (defcustom elpher-buttonify-urls-in-directories nil
169   "If non-nil, turns URLs matched in directories into clickable buttons."
170   :type '(boolean))
171
172 (defcustom elpher-cache-images nil
173   "If non-nil, cache images in memory in the same way as other content."
174   :type '(boolean))
175
176 (defcustom elpher-start-address nil
177   "If nil, the default start directory is shown when Elpher is started.
178 Otherwise, a list containing the selector, host and port of a directory to
179 use as the start page."
180   :type '(list string string integer))
181
182
183 ;;; Model
184 ;;
185
186 ;; Address
187
188 (defun elpher-make-address (selector host port)
189   "Create an address of a gopher object with SELECTOR, HOST and PORT."
190   (list selector host port))
191
192 (defun elpher-address-selector (address)
193   "Retrieve selector from ADDRESS."
194   (car address))
195
196 (defun elpher-address-host (address)
197   "Retrieve host from ADDRESS."
198   (cadr address))
199
200 (defun elpher-address-port (address)
201   "Retrieve port from ADDRESS."
202   (caddr address))
203
204 ;; Node
205
206 (defun elpher-make-node (parent address getter &optional content pos)
207   "Create a node in the gopher page hierarchy.
208
209 PARENT specifies the parent of the node, ADDRESS specifies the address of
210 the gopher page, GETTER provides the getter function used to obtain this
211 page.
212
213 The optional arguments CONTENT and POS can be used to fill the cached
214 content and cursor position fields of the node."
215   (list parent address getter content pos))
216
217 (defun elpher-node-parent (node)
218   "Retrieve the parent node of NODE."
219   (elt node 0))
220
221 (defun elpher-node-address (node)
222   "Retrieve the address of NODE."
223   (elt node 1))
224
225 (defun elpher-node-getter (node)
226   "Retrieve the preferred getter function of NODE."
227   (elt node 2))
228
229 (defun elpher-node-content (node)
230   "Retrieve the cached content of NODE, or nil if none exists."
231   (elt node 3))
232
233 (defun elpher-node-pos (node)
234   "Retrieve the cached cursor position for NODE, or nil if none exists."
235   (elt node 4))
236
237 (defun elpher-set-node-content (node content)
238   "Set the content cache of NODE to CONTENT."
239   (setcar (nthcdr 3 node) content))
240
241 (defun elpher-set-node-pos (node pos)
242   "Set the cursor position cache of NODE to POS."
243   (setcar (nthcdr 4 node) pos))
244
245 ;; Node graph traversal
246
247 (defvar elpher-current-node nil)
248
249 (defun elpher-visit-node (node &optional getter)
250   "Visit NODE using its own getter or GETTER, if non-nil."
251   (elpher-save-pos)
252   (elpher-process-cleanup)
253   (setq elpher-current-node node)
254   (if getter
255       (funcall getter)
256     (funcall (elpher-node-getter node))))
257
258 (defun elpher-visit-parent-node ()
259   "Visit the parent of the current node."
260   (let ((parent-node (elpher-node-parent elpher-current-node)))
261     (when parent-node
262       (elpher-visit-node parent-node))))
263       
264 (defun elpher-reload-current-node ()
265   "Reload the current node, discarding any existing cached content."
266   (elpher-set-node-content elpher-current-node nil)
267   (elpher-visit-node elpher-current-node))
268
269 (defun elpher-save-pos ()
270   "Save the current position of point to the current node."
271   (when elpher-current-node
272     (elpher-set-node-pos elpher-current-node (point))))
273
274 (defun elpher-restore-pos ()
275   "Restore the position of point to that cached in the current node."
276   (let ((pos (elpher-node-pos elpher-current-node)))
277     (if pos
278         (goto-char pos)
279       (goto-char (point-min)))))
280
281
282 ;;; Buffer preparation
283 ;;
284
285 (defmacro elpher-with-clean-buffer (&rest args)
286   "Evaluate ARGS with a clean *elpher* buffer as current."
287   (list 'with-current-buffer "*elpher*"
288         '(elpher-mode)
289         (append (list 'let '((inhibit-read-only t))
290                       '(erase-buffer))
291                 args)))
292
293
294 ;;; Index rendering
295 ;;
296
297 (defun elpher-insert-index (string)
298   "Insert the index corresponding to STRING into the current buffer."
299   ;; Should be able to split directly on CRLF, but some non-conformant
300   ;; LF-only servers sadly exist, hence the following.
301   (let* ((str-no-period (replace-regexp-in-string "\r\n\.\r\n$" "\r\n" string))
302          (str-no-cr (replace-regexp-in-string "\r" "" str-no-period)))
303     (dolist (line (split-string str-no-cr "\n"))
304       (unless (= (length line) 0)
305         (elpher-insert-index-record line)))))
306
307 (defun elpher-insert-margin (&optional type-name)
308   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
309   (if type-name
310       (progn
311         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
312                         (concat
313                          (propertize "[" 'face 'elpher-margin-brackets)
314                          (propertize type-name 'face 'elpher-margin-key)
315                          (propertize "]" 'face 'elpher-margin-brackets))))
316         (insert " "))
317     (insert (make-string elpher-margin-width ?\s))))
318
319 (defun elpher-node-button-help (node)
320   "Return a string containing the help text for a button corresponding to NODE."
321   (let ((address (elpher-node-address node)))
322     (if (eq (elpher-node-getter node) #'elpher-get-url)
323         (let ((url (cadr (split-string (elpher-address-selector address) "URL:"))))
324           (format "mouse-1, RET: open url '%s'" url))
325       (format "mouse-1, RET: open '%s' on %s port %s"
326               (elpher-address-selector address)
327               (elpher-address-host address)
328               (elpher-address-port address)))))
329
330 (defun elpher-insert-index-record (line)
331   "Insert the index record corresponding to LINE into the current buffer."
332   (let* ((type (elt line 0))
333          (fields (split-string (substring line 1) "\t"))
334          (display-string (elt fields 0))
335          (selector (elt fields 1))
336          (host (elt fields 2))
337          (port (elt fields 3)))
338     (elpher-insert-index-record-helper type display-string selector host port)))
339
340 (defun elpher-insert-index-record-helper (type display-string selector host port)
341   "Helper function to insert an index record into the current buffer.
342 The contents of the record are dictated by TYPE, DISPLAY-STRING, SELECTOR, HOST
343 and PORT.
344
345 This function is essentially the second half of `elpher-insert-index-record',
346 but broken out so that it can be used by other functions to construct indices
347 on the fly."
348   (let ((address (elpher-make-address selector host port))
349         (type-map-entry (alist-get type elpher-type-map)))
350     (if type-map-entry
351         (let* ((getter (car type-map-entry))
352                (margin-code (cadr type-map-entry))
353                (face (caddr type-map-entry))
354                (node (elpher-make-node elpher-current-node address getter)))
355           (elpher-insert-margin margin-code)
356           (insert-text-button display-string
357                               'face face
358                               'elpher-node node
359                               'elpher-node-type type
360                               'action #'elpher-click-link
361                               'follow-link t
362                               'help-echo (elpher-node-button-help node)))
363       (pcase type
364         (?i (elpher-insert-margin) ;; Information
365             (insert (propertize
366                      (if elpher-buttonify-urls-in-directories
367                          (elpher-buttonify-urls display-string)
368                        display-string)
369                      'face 'elpher-info)))
370         (tp (elpher-insert-margin (concat (char-to-string tp) "?"))
371             (insert (propertize display-string
372                                 'face 'elpher-unknown-face)))))
373     (insert "\n")))
374
375 (defun elpher-click-link (button)
376   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
377   (let ((node (button-get button 'elpher-node)))
378     (elpher-visit-node node)))
379
380
381 ;;; Selector retrieval (all kinds)
382 ;;
383
384 (defun elpher-process-cleanup ()
385   "Immediately shut down any extant elpher process."
386   (let ((p (get-process "elpher-process")))
387     (if p (delete-process p))))
388
389 (defvar elpher-selector-string)
390
391 (defun elpher-get-selector (address after)
392   "Retrieve selector specified by ADDRESS, then execute AFTER.
393 The result is stored as a string in the variable â€˜elpher-selector-string’."
394   (setq elpher-selector-string "")
395   (make-network-process
396    :name "elpher-process"
397    :host (elpher-address-host address)
398    :service (elpher-address-port address)
399    :filter (lambda (proc string)
400              (setq elpher-selector-string (concat elpher-selector-string string)))
401    :sentinel after)
402   (process-send-string "elpher-process"
403                        (concat (elpher-address-selector address) "\n")))
404
405 ;; Index retrieval
406
407 (defun elpher-get-index-node ()
408   "Getter which retrieves the current node contents as an index."
409   (let ((content (elpher-node-content elpher-current-node))
410         (address (elpher-node-address elpher-current-node)))
411     (if content
412         (progn
413           (elpher-with-clean-buffer
414            (insert content)
415            (elpher-restore-pos)))
416       (if address
417           (progn
418             (elpher-with-clean-buffer
419              (insert "LOADING DIRECTORY..."))
420             (elpher-get-selector address
421                                   (lambda (proc event)
422                                     (unless (string-prefix-p "deleted" event)
423                                       (elpher-with-clean-buffer
424                                        (elpher-insert-index elpher-selector-string)
425                                        (elpher-restore-pos)
426                                        (elpher-set-node-content elpher-current-node
427                                                                 (buffer-string)))))))
428         (progn
429           (elpher-with-clean-buffer
430            (elpher-insert-index elpher-start-index)
431            (elpher-restore-pos)
432            (elpher-set-node-content elpher-current-node
433                                     (buffer-string))))))))
434
435 ;; Text retrieval
436
437 (defconst elpher-url-regex
438   "\\([a-zA-Z]+\\)://\\([a-zA-Z0-9.\-]+\\)\\(?3::[0-9]+\\)?\\(?4:/[^ \r\n\t(),]*\\)?"
439   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
440
441 (defun elpher-buttonify-urls (string)
442   "Turn substrings which look like urls in STRING into clickable buttons."
443   (with-temp-buffer
444     (insert string)
445     (goto-char (point-min))
446     (while (re-search-forward elpher-url-regex nil t)
447       (let ((url (match-string 0))
448             (protocol (downcase (match-string 1))))
449         (let ((node
450                (if (string= protocol "gopher")
451                    (let* ((host (match-string 2))
452                           (port (if (> (length (match-string 3))  1)
453                                     (string-to-number (substring (match-string 3) 1))
454                                   70))
455                           (type-and-selector (match-string 4))
456                           (type (if (> (length type-and-selector) 1)
457                                     (elt type-and-selector 1)
458                                   ?1))
459                           (selector (if (> (length type-and-selector) 1)
460                                         (substring type-and-selector 2)
461                                       ""))
462                           (address (elpher-make-address selector host port))
463                           (getter (car (alist-get type elpher-type-map))))
464                      (elpher-make-node elpher-current-node address getter))
465                  (let* ((host (match-string 2))
466                         (port (if (> (length (match-string 3)) 1)
467                                   (string-to-number (substring (match-string 3) 1))
468                                 70))
469                         (selector (concat "URL:" url))
470                         (address (elpher-make-address selector host port))
471                         (getter (car (alist-get ?h elpher-type-map))))
472                    (elpher-make-node elpher-current-node address getter)))))
473           (make-text-button (match-beginning 0)
474                             (match-end 0)
475                             'elpher-node  node
476                             'action #'elpher-click-link
477                             'follow-link t
478                             'help-echo (elpher-node-button-help node)))))
479     (buffer-string)))
480
481 (defun elpher-process-text (string)
482   "Remove CRs and trailing period from the gopher text document STRING."
483   (let* ((chopped-str (replace-regexp-in-string "\r\n\.\r\n$" "\r\n" string))
484          (cleaned-str (replace-regexp-in-string "\r" "" chopped-str)))
485     (elpher-buttonify-urls cleaned-str)))
486
487 (defun elpher-get-text-node ()
488   "Getter which retrieves the current node contents as a text document."
489   (let ((content (elpher-node-content elpher-current-node))
490         (address (elpher-node-address elpher-current-node)))
491     (if content
492         (progn
493           (elpher-with-clean-buffer
494            (insert content)
495            (elpher-restore-pos)))
496       (progn
497         (elpher-with-clean-buffer
498          (insert "LOADING TEXT..."))
499         (elpher-get-selector address
500                               (lambda (proc event)
501                                 (unless (string-prefix-p "deleted" event)
502                                   (elpher-with-clean-buffer
503                                    (insert (elpher-process-text elpher-selector-string))
504                                    (elpher-restore-pos)
505                                    (elpher-set-node-content elpher-current-node
506                                                             (buffer-string))))))))))
507
508 ;; Image retrieval
509
510 (defun elpher-get-image-node ()
511   "Getter which retrieves the current node contents as an image to view."
512   (let ((content (elpher-node-content elpher-current-node))
513         (address (elpher-node-address elpher-current-node)))
514     (if content
515         (progn
516           (elpher-with-clean-buffer
517            (insert-image content)
518            (elpher-restore-pos)))
519       (if (display-images-p)
520           (progn
521             (elpher-with-clean-buffer
522              (insert "LOADING IMAGE..."))
523             (elpher-get-selector address
524                                  (lambda (proc event)
525                                    (unless (string-prefix-p "deleted" event)
526                                      (let ((image (create-image
527                                                    (encode-coding-string elpher-selector-string
528                                                                          'no-conversion)
529                                                    nil t)))
530                                        (elpher-with-clean-buffer
531                                         (insert-image image)
532                                         (elpher-restore-pos))
533                                        (if elpher-cache-images
534                                            (elpher-set-node-content elpher-current-node
535                                                                     image)))))))
536         (elpher-get-node-download)))))
537
538 ;; Search retrieval
539
540 (defun elpher-get-search-node ()
541   "Getter which submits a search query to the address of the current node."
542   (let ((content (elpher-node-content elpher-current-node))
543         (address (elpher-node-address elpher-current-node))
544         (aborted t))
545     (if content
546         (progn
547           (elpher-with-clean-buffer
548            (insert content)
549            (elpher-restore-pos))
550           (message "Displaying cached search results.  Reload to perform a new search."))
551       (unwind-protect
552           (let* ((query-string (read-string "Query: "))
553                  (query-selector (concat (elpher-address-selector address) "\t" query-string))
554                  (search-address (elpher-make-address query-selector
555                                                        (elpher-address-host address)
556                                                        (elpher-address-port address))))
557             (setq aborted nil)
558             (elpher-with-clean-buffer
559              (insert "LOADING RESULTS..."))
560             (elpher-get-selector search-address
561                                   (lambda (proc event)
562                                     (unless (string-prefix-p "deleted" event)
563                                       (elpher-with-clean-buffer
564                                        (elpher-insert-index elpher-selector-string))
565                                       (goto-char (point-min))
566                                       (elpher-set-node-content elpher-current-node
567                                                                 (buffer-string))))))
568         (if aborted
569             (elpher-visit-parent-node))))))
570
571 ;; Raw server response retrieval
572
573 (defun elpher-get-node-raw ()
574   "Getter which retrieves the raw server response for the current node."
575   (let* ((content (elpher-node-content elpher-current-node))
576          (address (elpher-node-address elpher-current-node)))
577     (elpher-with-clean-buffer
578      (insert "LOADING RAW SERVER RESPONSE..."))
579     (if address
580         (elpher-get-selector address
581                               (lambda (proc event)
582                                 (unless (string-prefix-p "deleted" event)
583                                   (elpher-with-clean-buffer
584                                    (insert elpher-selector-string)
585                                    (goto-char (point-min))))))
586       (progn
587         (elpher-with-clean-buffer
588          (insert elpher-start-index))
589         (goto-char (point-min)))))
590   (message "Displaying raw server response.  Reload or redraw to return to standard view."))
591  
592 ;; File export retrieval
593
594 (defvar elpher-download-filename)
595
596 (defun elpher-get-node-download ()
597   "Getter which retrieves the current node and writes the result to a file."
598   (let* ((address (elpher-node-address elpher-current-node))
599          (selector (elpher-address-selector address)))
600     (elpher-visit-parent-node) ; Do first in case of non-local exits.
601     (let* ((filename-proposal (file-name-nondirectory selector))
602            (filename (read-file-name "Save file as: "
603                                      nil nil nil
604                                      (if (> (length filename-proposal) 0)
605                                          filename-proposal
606                                        "gopher.file"))))
607       (message "Downloading...")
608       (setq elpher-download-filename filename)
609       (elpher-get-selector address
610                             (lambda (proc event)
611                               (let ((coding-system-for-write 'binary))
612                                 (with-temp-file elpher-download-filename
613                                   (insert elpher-selector-string)
614                                   (message (format "Download complate, saved to file %s."
615                                                    elpher-download-filename)))))))))
616
617 ;; URL retrieval
618
619 (defun elpher-get-url ()
620   "Getter which attempts to open the URL specified by the current node."
621   (let* ((address (elpher-node-address elpher-current-node))
622          (selector (elpher-address-selector address)))
623     (elpher-visit-parent-node) ; Do first in case of non-local exits.
624     (let ((url (elt (split-string selector "URL:") 1)))
625       (if elpher-open-urls-with-eww
626           (browse-web url)
627         (browse-url url)))))
628
629 ;;; Bookmarks
630 ;;
631
632 (defun elpher-make-bookmark (type display-string address)
633   (list type display-string address))
634   
635 (defun elpher-bookmark-type (bookmark)
636   (elt bookmark 0))
637
638 (defun elpher-bookmark-display-string (bookmark)
639   (elt bookmark 1))
640
641 (defun elpher-bookmark-address (bookmark)
642   (elt bookmark 2))
643
644 (defun elpher-save-bookmarks (bookmarks)
645   (with-temp-file (locate-user-emacs-file "elpher-bookmarks")
646     (erase-buffer)
647     (pp bookmarks (current-buffer))))
648
649 (defun elpher-load-bookmarks ()
650   (with-temp-buffer 
651     (ignore-errors
652       (insert-file-contents (locate-user-emacs-file "elpher-bookmarks"))
653       (goto-char (point-min))
654       (read (current-buffer)))))
655
656 (defun elpher-add-bookmark (bookmark)
657   (let ((bookmarks (elpher-load-bookmarks)))
658     (add-to-list 'bookmarks bookmark)
659     (elpher-save-bookmarks bookmarks)))
660
661 (defun elpher-remove-bookmark (bookmark)
662   (elpher-save-bookmarks
663    (seq-filter (lambda (this-bookmark)
664                  (not (equal bookmark this-bookmark)))
665                (elpher-load-bookmarks))))
666      
667 (defun elpher-display-bookmarks ()
668   (interactive)
669   (elpher-with-clean-buffer
670    (insert
671     "Use 'u' to return to the previous page.\n\n"
672     "---- Bookmark list ----\n\n")
673    (let ((bookmarks (elpher-load-bookmarks)))
674      (if bookmarks
675          (dolist (bookmark (elpher-load-bookmarks))
676            (let ((type (elpher-bookmark-type bookmark))
677                  (display-string (elpher-bookmark-display-string bookmark))
678                  (address (elpher-bookmark-address bookmark)))
679              (elpher-insert-index-record-helper type display-string
680                                                 (elpher-address-selector address)
681                                                 (elpher-address-host address)
682                                                 (elpher-address-port address))))
683        (insert "No bookmarks found.\n")))
684    (insert "\n-----------------------")
685    (goto-char (point-min))
686    (elpher-next-link)))
687
688 (defun elpher-bookmark-link ()
689   "Bookmark the link at point."
690   (interactive)
691   (let ((button (button-at (point))))
692     (if button
693         (let ((node (button-get button 'elpher-node))
694               (type (button-get button 'elpher-node-type))
695               (label (button-label button)))
696           (if node
697               (progn
698                 (elpher-add-bookmark
699                  (elpher-make-bookmark type
700                                        label
701                                        (elpher-node-address node)))
702                 (message "Bookmarked \"%s\"" label))
703             (error "Can only bookmark gopher links, not general URLs.")))
704       (error "No link selected."))))
705
706 (defun elpher-unbookmark-link ()
707   "Remove bookmark for the link at point."
708   (interactive)
709   (let ((button (button-at (point))))
710     (if button
711         (let ((node (button-get button 'elpher-node))
712               (type (button-get button 'elpher-node-type)))
713           (if node
714               (elpher-remove-bookmark 
715                (elpher-make-bookmark type
716                                      (button-label button)
717                                      (elpher-node-address node)))
718             (error "Can only bookmark gopher links, not general URLs.")))
719       (error "No link selected."))))
720
721 ;;; Interactive navigation procedures
722 ;;
723
724 (defun elpher-next-link ()
725   "Move point to the next link on the current page."
726   (interactive)
727   (forward-button 1))
728
729 (defun elpher-prev-link ()
730   "Move point to the previous link on the current page."
731   (interactive)
732   (backward-button 1))
733
734 (defun elpher-follow-current-link ()
735   "Open the link or url at point."
736   (interactive)
737   (push-button))
738
739 (defun elpher-go ()
740   "Go to a particular gopher site."
741   (interactive)
742   (switch-to-buffer "*elpher*")
743   (let* (
744          (hostname (read-string "Gopher host: "))
745          (selector (read-string "Selector (default none): " nil nil ""))
746          (port (read-string "Port (default 70): " nil nil 70))
747          (address (list selector hostname port)))
748     (elpher-visit-node
749      (elpher-make-node elpher-current-node
750                         address
751                         #'elpher-get-index-node))))
752
753 (defun  elpher-redraw ()
754   "Redraw current page."
755   (interactive)
756   (if elpher-current-node
757       (elpher-visit-node elpher-current-node)
758     (message "No current site.")))
759
760 (defun  elpher-reload ()
761   "Reload current page."
762   (interactive)
763   (if elpher-current-node
764       (elpher-reload-current-node)
765     (message "No current site.")))
766
767 (defun elpher-view-raw ()
768   "View current page as plain text."
769   (interactive)
770   (if elpher-current-node
771       (elpher-visit-node elpher-current-node
772                          #'elpher-get-node-raw)
773     (message "No current site.")))
774
775 (defun elpher-back ()
776   "Go to previous site."
777   (interactive)
778   (if (elpher-node-parent elpher-current-node)
779       (elpher-visit-parent-node)
780     (error "No previous site.")))
781
782 (defun elpher-download ()
783   "Download the link at point."
784   (interactive)
785   (let ((button (button-at (point))))
786     (if button
787         (let ((node (button-get button 'elpher-node)))
788           (if node
789               (elpher-visit-node (button-get button 'elpher-node)
790                                  #'elpher-get-node-download)
791             (error "Can only download gopher links, not general URLs.")))
792       (error "No link selected."))))
793
794 (defun elpher-build-link-map ()
795   "Build alist mapping link names to destination nodes in current buffer."
796   (let ((link-map nil)
797         (b (next-button (point-min) t)))
798     (while b
799       (add-to-list 'link-map (cons (button-label b) b))
800       (setq b (next-button (button-start b))))
801     link-map))
802
803 (defun elpher-menu ()
804   "Select a directory entry by name.  Similar to the info browser (m)enu command."
805   (interactive)
806   (let* ((link-map (elpher-build-link-map)))
807     (if link-map
808         (let ((key (let ((completion-ignore-case t))
809                      (completing-read "Directory entry/link (tab to autocomplete): "
810                                       link-map nil t))))
811           (if (and key (> (length key) 0))
812               (let ((b (cdr (assoc key link-map))))
813                 (goto-char (button-start b))
814                 (button-activate b)))))))
815
816 (defun elpher-root-dir ()
817   "Visit root of current server."
818   (interactive)
819   (let ((address (elpher-node-address elpher-current-node)))
820     (if address
821         (let ((host (elpher-address-host address))
822               (selector (elpher-address-selector address))
823               (port (elpher-address-port address)))
824           (if (> (length selector) 0)
825               (let ((root-address (elpher-make-address "" host port)))
826                 (elpher-visit-node (elpher-make-node elpher-current-node
827                                                      root-address
828                                                      #'elpher-get-index-node)))
829             (error "Already at root directory of current server.")))
830       (error "Command invalid for Elpher start page."))))
831
832
833 ;;; Mode and keymap
834 ;;
835
836 (defvar elpher-mode-map
837   (let ((map (make-sparse-keymap)))
838     (define-key map (kbd "TAB") 'elpher-next-link)
839     (define-key map (kbd "<backtab>") 'elpher-prev-link)
840     (define-key map (kbd "u") 'elpher-back)
841     (define-key map (kbd "O") 'elpher-root-dir)
842     (define-key map (kbd "g") 'elpher-go)
843     (define-key map (kbd "r") 'elpher-redraw)
844     (define-key map (kbd "R") 'elpher-reload)
845     (define-key map (kbd "w") 'elpher-view-raw)
846     (define-key map (kbd "d") 'elpher-download)
847     (define-key map (kbd "m") 'elpher-menu)
848     (when (fboundp 'evil-define-key)
849       (add-to-list 'evil-motion-state-modes 'elpher-mode)
850       (evil-define-key 'motion map
851         (kbd "TAB") 'elpher-next-link
852         (kbd "C-]") 'elpher-follow-current-link
853         (kbd "C-t") 'elpher-back
854         (kbd "u") 'elpher-back
855         (kbd "O") 'elpher-root-dir
856         (kbd "g") 'elpher-go
857         (kbd "r") 'elpher-redraw
858         (kbd "R") 'elpher-reload
859         (kbd "w") 'elpher-view-raw
860         (kbd "d") 'elpher-download
861         (kbd "m") 'elpher-menu
862         (kbd "a") 'elpher-bookmark-link
863         (kbd "x") 'elpher-unbookmark-link
864         (kbd "B") 'elpher-display-bookmarks))
865     map)
866   "Keymap for gopher client.")
867
868 (define-derived-mode elpher-mode special-mode "elpher"
869   "Major mode for elpher, an elisp gopher client.")
870
871
872 ;;; Main start procedure
873 ;;
874
875 ;;;###autoload
876 (defun elpher ()
877   "Start elpher with default landing page."
878   (interactive)
879   (if (get-buffer "*elpher*")
880       (switch-to-buffer "*elpher*")
881     (switch-to-buffer "*elpher*")
882     (setq elpher-current-node nil)
883     (let ((start-node (elpher-make-node nil
884                                         elpher-start-address
885                                         #'elpher-get-index-node)))
886       (elpher-visit-node start-node)))
887   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
888
889 ;;; elpher.el ends here