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