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