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