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