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