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