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