Port section of gopher URLs is now used.
[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 (if (> (length (match-string 3))  1)
450                              (string-to-number (substring (match-string 3) 1))
451                            70))
452                    (type-and-selector (match-string 4))
453                    (type (if (> (length type-and-selector) 1)
454                              (elt type-and-selector 1)
455                            ?1))
456                    (selector (if (> (length type-and-selector) 1)
457                                  (substring type-and-selector 2)
458                                ""))
459                    (address (elpher-make-address selector host port))
460                    (getter (car (alist-get type elpher-type-map))))
461               (make-text-button (match-beginning 0)
462                                 (match-end 0)
463                                 'elpher-node (elpher-make-node elpher-current-node
464                                                                  address
465                                                                  getter)
466                                 'action #'elpher-click-link
467                                 'follow-link t
468                                 'help-echo (format "mouse-1, RET: open '%s' on %s port %s"
469                                                    selector host port)))
470           (make-text-button (match-beginning 0)
471                             (match-end 0)
472                             'elpher-url url
473                             'action #'elpher-click-url
474                             'follow-link t
475                             'help-echo (format "mouse-1, RET: open url %s" url)))))
476     (buffer-string)))
477
478 (defun elpher-process-text (string)
479   "Remove CRs and trailing period from the gopher text document STRING."
480   (let* ((chopped-str (replace-regexp-in-string "\r\n\.\r\n$" "\r\n" string))
481          (cleaned-str (replace-regexp-in-string "\r" "" chopped-str)))
482     (elpher-buttonify-urls cleaned-str)))
483
484 (defun elpher-get-text-node ()
485   "Getter which retrieves the current node contents as a text document."
486   (let ((content (elpher-node-content elpher-current-node))
487         (address (elpher-node-address elpher-current-node)))
488     (if content
489         (progn
490           (elpher-with-clean-buffer
491            (insert content)
492            (elpher-restore-pos)))
493       (progn
494         (elpher-with-clean-buffer
495          (insert "LOADING TEXT..."))
496         (elpher-get-selector address
497                               (lambda (proc event)
498                                 (unless (string-prefix-p "deleted" event)
499                                   (elpher-with-clean-buffer
500                                    (insert (elpher-process-text elpher-selector-string))
501                                    (elpher-restore-pos)
502                                    (elpher-set-node-content elpher-current-node
503                                                             (buffer-string))))))))))
504
505 ;; Image retrieval
506
507 (defun elpher-get-image-node ()
508   "Getter which retrieves the current node contents as an image to view."
509   (let ((content (elpher-node-content elpher-current-node))
510         (address (elpher-node-address elpher-current-node)))
511     (if content
512         (progn
513           (elpher-with-clean-buffer
514            (insert-image content)
515            (elpher-restore-pos)))
516       (if (display-images-p)
517           (progn
518             (elpher-with-clean-buffer
519              (insert "LOADING IMAGE..."))
520             (elpher-get-selector address
521                                  (lambda (proc event)
522                                    (unless (string-prefix-p "deleted" event)
523                                      (let ((image (create-image
524                                                    (encode-coding-string elpher-selector-string
525                                                                          'no-conversion)
526                                                    nil t)))
527                                        (elpher-with-clean-buffer
528                                         (insert-image image)
529                                         (elpher-restore-pos))
530                                        (if elpher-cache-images
531                                            (elpher-set-node-content elpher-current-node
532                                                                     image)))))))
533         (elpher-get-node-download)))))
534
535 ;; Search retrieval
536
537 (defun elpher-get-search-node ()
538   "Getter which submits a search query to the address of the current node."
539   (let ((content (elpher-node-content elpher-current-node))
540         (address (elpher-node-address elpher-current-node))
541         (aborted t))
542     (if content
543         (progn
544           (elpher-with-clean-buffer
545            (insert content)
546            (elpher-restore-pos))
547           (message "Displaying cached search results.  Reload to perform a new search."))
548       (unwind-protect
549           (let* ((query-string (read-string "Query: "))
550                  (query-selector (concat (elpher-address-selector address) "\t" query-string))
551                  (search-address (elpher-make-address query-selector
552                                                        (elpher-address-host address)
553                                                        (elpher-address-port address))))
554             (setq aborted nil)
555             (elpher-with-clean-buffer
556              (insert "LOADING RESULTS..."))
557             (elpher-get-selector search-address
558                                   (lambda (proc event)
559                                     (unless (string-prefix-p "deleted" event)
560                                       (elpher-with-clean-buffer
561                                        (elpher-insert-index elpher-selector-string))
562                                       (goto-char (point-min))
563                                       (elpher-set-node-content elpher-current-node
564                                                                 (buffer-string))))))
565         (if aborted
566             (elpher-visit-parent-node))))))
567
568 ;; Raw server response retrieval
569
570 (defun elpher-get-node-raw ()
571   "Getter which retrieves the raw server response for the current node."
572   (let* ((content (elpher-node-content elpher-current-node))
573          (address (elpher-node-address elpher-current-node)))
574     (elpher-with-clean-buffer
575      (insert "LOADING RAW SERVER RESPONSE..."))
576     (if address
577         (elpher-get-selector address
578                               (lambda (proc event)
579                                 (unless (string-prefix-p "deleted" event)
580                                   (elpher-with-clean-buffer
581                                    (insert elpher-selector-string)
582                                    (goto-char (point-min))))))
583       (progn
584         (elpher-with-clean-buffer
585          (insert elpher-start-index))
586         (goto-char (point-min)))))
587   (message "Displaying raw server response.  Reload or redraw to return to standard view."))
588  
589 ;; File export retrieval
590
591 (defvar elpher-download-filename)
592
593 (defun elpher-get-node-download ()
594   "Getter which retrieves the current node and writes the result to a file."
595   (let* ((address (elpher-node-address elpher-current-node))
596          (selector (elpher-address-selector address)))
597     (elpher-visit-parent-node) ; Do first in case of non-local exits.
598     (let* ((filename-proposal (file-name-nondirectory selector))
599            (filename (read-file-name "Save file as: "
600                                      nil nil nil
601                                      (if (> (length filename-proposal) 0)
602                                          filename-proposal
603                                        "gopher.file"))))
604       (message "Downloading...")
605       (setq elpher-download-filename filename)
606       (elpher-get-selector address
607                             (lambda (proc event)
608                               (let ((coding-system-for-write 'binary))
609                                 (with-temp-file elpher-download-filename
610                                   (insert elpher-selector-string)
611                                   (message (format "Download complate, saved to file %s."
612                                                    elpher-download-filename)))))))))
613
614 ;;; Bookmarks
615 ;;
616
617 (defun elpher-make-bookmark (type display-string address)
618   (list type display-string address))
619   
620 (defun elpher-bookmark-type (bookmark)
621   (elt bookmark 0))
622
623 (defun elpher-bookmark-display-string (bookmark)
624   (elt bookmark 1))
625
626 (defun elpher-bookmark-address (bookmark)
627   (elt bookmark 2))
628
629 (defun elpher-save-bookmarks (bookmarks)
630   (with-temp-file (locate-user-emacs-file "elpher-bookmarks")
631     (erase-buffer)
632     (pp bookmarks (current-buffer))))
633
634 (defun elpher-load-bookmarks ()
635   (with-temp-buffer 
636     (ignore-errors
637       (insert-file-contents (locate-user-emacs-file "elpher-bookmarks"))
638       (goto-char (point-min))
639       (read (current-buffer)))))
640
641 (defun elpher-add-bookmark (bookmark)
642   (let ((bookmarks (elpher-load-bookmarks)))
643     (add-to-list 'bookmarks bookmark)
644     (elpher-save-bookmarks bookmarks)))
645
646 (defun elpher-remove-bookmark (bookmark)
647   (elpher-save-bookmarks
648    (seq-filter (lambda (this-bookmark)
649                  (not (equal bookmark this-bookmark)))
650                (elpher-load-bookmarks))))
651      
652 (defun elpher-display-bookmarks ()
653   (interactive)
654   (elpher-with-clean-buffer
655    (insert
656     "Use 'u' to return to the previous page.\n\n"
657     "---- Bookmark list ----\n\n")
658    (let ((bookmarks (elpher-load-bookmarks)))
659      (if bookmarks
660          (dolist (bookmark (elpher-load-bookmarks))
661            (let ((type (elpher-bookmark-type bookmark))
662                  (display-string (elpher-bookmark-display-string bookmark))
663                  (address (elpher-bookmark-address bookmark)))
664              (elpher-insert-index-record-helper type display-string
665                                                 (elpher-address-selector address)
666                                                 (elpher-address-host address)
667                                                 (elpher-address-port address))))
668        (insert "No bookmarks found.\n")))
669    (insert "\n-----------------------")
670    (goto-char (point-min))
671    (elpher-next-link)))
672
673 (defun elpher-bookmark-link ()
674   "Bookmark the link at point."
675   (interactive)
676   (let ((button (button-at (point))))
677     (if button
678         (let ((node (button-get button 'elpher-node))
679               (type (button-get button 'elpher-node-type))
680               (label (button-label button)))
681           (if node
682               (progn
683                 (elpher-add-bookmark
684                  (elpher-make-bookmark type
685                                        label
686                                        (elpher-node-address node)))
687                 (message "Bookmarked \"%s\"" label))
688             (error "Can only bookmark gopher links, not general URLs.")))
689       (error "No link selected."))))
690
691 (defun elpher-unbookmark-link ()
692   "Remove bookmark for the link at point."
693   (interactive)
694   (let ((button (button-at (point))))
695     (if button
696         (let ((node (button-get button 'elpher-node))
697               (type (button-get button 'elpher-node-type)))
698           (if node
699               (elpher-remove-bookmark 
700                (elpher-make-bookmark type
701                                      (button-label button)
702                                      (elpher-node-address node)))
703             (error "Can only bookmark gopher links, not general URLs.")))
704       (error "No link selected."))))
705
706 ;;; Interactive navigation procedures
707 ;;
708
709 (defun elpher-next-link ()
710   "Move point to the next link on the current page."
711   (interactive)
712   (forward-button 1))
713
714 (defun elpher-prev-link ()
715   "Move point to the previous link on the current page."
716   (interactive)
717   (backward-button 1))
718
719 (defun elpher-follow-current-link ()
720   "Open the link or url at point."
721   (interactive)
722   (push-button))
723
724 (defun elpher-go ()
725   "Go to a particular gopher site."
726   (interactive)
727   (switch-to-buffer "*elpher*")
728   (let* (
729          (hostname (read-string "Gopher host: "))
730          (selector (read-string "Selector (default none): " nil nil ""))
731          (port (read-string "Port (default 70): " nil nil 70))
732          (address (list selector hostname port)))
733     (elpher-visit-node
734      (elpher-make-node elpher-current-node
735                         address
736                         #'elpher-get-index-node))))
737
738 (defun  elpher-redraw ()
739   "Redraw current page."
740   (interactive)
741   (if elpher-current-node
742       (elpher-visit-node elpher-current-node)
743     (message "No current site.")))
744
745 (defun  elpher-reload ()
746   "Reload current page."
747   (interactive)
748   (if elpher-current-node
749       (elpher-reload-current-node)
750     (message "No current site.")))
751
752 (defun elpher-view-raw ()
753   "View current page as plain text."
754   (interactive)
755   (if elpher-current-node
756       (elpher-visit-node elpher-current-node
757                          #'elpher-get-node-raw)
758     (message "No current site.")))
759
760 (defun elpher-back ()
761   "Go to previous site."
762   (interactive)
763   (if (elpher-node-parent elpher-current-node)
764       (elpher-visit-parent-node)
765     (error "No previous site.")))
766
767 (defun elpher-download ()
768   "Download the link at point."
769   (interactive)
770   (let ((button (button-at (point))))
771     (if button
772         (let ((node (button-get button 'elpher-node)))
773           (if node
774               (elpher-visit-node (button-get button 'elpher-node)
775                                  #'elpher-get-node-download)
776             (error "Can only download gopher links, not general URLs.")))
777       (error "No link selected."))))
778
779 (defun elpher-build-link-map ()
780   "Build alist mapping link names to destination nodes in current buffer."
781   (let ((link-map nil)
782         (b (next-button (point-min) t)))
783     (while b
784       (add-to-list 'link-map (cons (button-label b) b))
785       (setq b (next-button (button-start b))))
786     link-map))
787
788 (defun elpher-menu ()
789   "Select a directory entry by name.  Similar to the info browser (m)enu command."
790   (interactive)
791   (let* ((link-map (elpher-build-link-map)))
792     (if link-map
793         (let ((key (let ((completion-ignore-case t))
794                      (completing-read "Directory entry/link (tab to autocomplete): "
795                                       link-map nil t))))
796           (if (and key (> (length key) 0))
797               (let ((b (cdr (assoc key link-map))))
798                 (goto-char (button-start b))
799                 (button-activate b)))))))
800
801 (defun elpher-root-dir ()
802   "Visit root of current server."
803   (interactive)
804   (let ((address (elpher-node-address elpher-current-node)))
805     (if address
806         (let ((host (elpher-address-host address))
807               (selector (elpher-address-selector address))
808               (port (elpher-address-port address)))
809           (if (> (length selector) 0)
810               (let ((root-address (elpher-make-address "" host port)))
811                 (elpher-visit-node (elpher-make-node elpher-current-node
812                                                      root-address
813                                                      #'elpher-get-index-node)))
814             (error "Already at root directory of current server.")))
815       (error "Command invalid for Elpher start page."))))
816
817
818 ;;; Mode and keymap
819 ;;
820
821 (defvar elpher-mode-map
822   (let ((map (make-sparse-keymap)))
823     (define-key map (kbd "TAB") 'elpher-next-link)
824     (define-key map (kbd "<backtab>") 'elpher-prev-link)
825     (define-key map (kbd "u") 'elpher-back)
826     (define-key map (kbd "O") 'elpher-root-dir)
827     (define-key map (kbd "g") 'elpher-go)
828     (define-key map (kbd "r") 'elpher-redraw)
829     (define-key map (kbd "R") 'elpher-reload)
830     (define-key map (kbd "w") 'elpher-view-raw)
831     (define-key map (kbd "d") 'elpher-download)
832     (define-key map (kbd "m") 'elpher-menu)
833     (when (fboundp 'evil-define-key)
834       (add-to-list 'evil-motion-state-modes 'elpher-mode)
835       (evil-define-key 'motion map
836         (kbd "TAB") 'elpher-next-link
837         (kbd "C-]") 'elpher-follow-current-link
838         (kbd "C-t") 'elpher-back
839         (kbd "u") 'elpher-back
840         (kbd "O") 'elpher-root-dir
841         (kbd "g") 'elpher-go
842         (kbd "r") 'elpher-redraw
843         (kbd "R") 'elpher-reload
844         (kbd "w") 'elpher-view-raw
845         (kbd "d") 'elpher-download
846         (kbd "m") 'elpher-menu
847         (kbd "a") 'elpher-bookmark-link
848         (kbd "x") 'elpher-unbookmark-link
849         (kbd "B") 'elpher-display-bookmarks))
850     map)
851   "Keymap for gopher client.")
852
853 (define-derived-mode elpher-mode special-mode "elpher"
854   "Major mode for elpher, an elisp gopher client.")
855
856
857 ;;; Main start procedure
858 ;;
859
860 ;;;###autoload
861 (defun elpher ()
862   "Start elpher with default landing page."
863   (interactive)
864   (if (get-buffer "*elpher*")
865       (switch-to-buffer "*elpher*")
866     (switch-to-buffer "*elpher*")
867     (setq elpher-current-node nil)
868     (let ((start-node (elpher-make-node nil
869                                         elpher-start-address
870                                         #'elpher-get-index-node)))
871       (elpher-visit-node start-node)))
872   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
873
874 ;;; elpher.el ends here