Type now part of address.
[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     (?4 elpher-get-node-download "B" elpher-binary)
102     (?5 elpher-get-node-download "B" elpher-binary)
103     (?7 elpher-get-search-node "?" elpher-search)
104     (?8 elpher-get-telnet-node "?" elpher-telnet)
105     (?9 elpher-get-node-download "B" elpher-binary)
106     (?g elpher-get-image-node "im" elpher-image)
107     (?p elpher-get-image-node "im" elpher-image)
108     (?I elpher-get-image-node "im" elpher-image)
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 (type selector host port)
194   "Create an address of a gopher object with SELECTOR, HOST and PORT."
195   (list type selector host port))
196
197 (defun elpher-address-type (address)
198   "Retrieve type from ADDRESS."
199   (elt address 0))
200
201 (defun elpher-address-selector (address)
202   "Retrieve selector from ADDRESS."
203   (elt address 1))
204
205 (defun elpher-address-host (address)
206   "Retrieve host from ADDRESS."
207   (elt address 2))
208
209 (defun elpher-address-port (address)
210   "Retrieve port from ADDRESS."
211   (elt address 3))
212
213 ;; Node
214
215 (defun elpher-make-node (parent address &optional display-string content pos)
216   "Create a node in the gopher page hierarchy.
217
218 PARENT specifies the parent of the node, and ADDRESS specifies the
219 address of the gopher page.
220
221 The optional arguments CONTENT and POS can be used to fill the cached
222 content and cursor position fields of the node."
223   (list parent address content pos))
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-content (node)
234   "Retrieve the cached content of NODE, or nil if none exists."
235   (elt node 2))
236
237 (defun elpher-node-pos (node)
238   "Retrieve the cached cursor position for NODE, or nil if none exists."
239   (elt node 3))
240
241 (defun elpher-set-node-content (node content)
242   "Set the content cache of NODE to CONTENT."
243   (setcar (nthcdr 2 node) content))
244
245 (defun elpher-set-node-pos (node pos)
246   "Set the cursor position cache of NODE to POS."
247   (setcar (nthcdr 3 node) pos))
248
249 ;; Node graph traversal
250
251 (defvar elpher-current-node nil)
252
253 (defun elpher-visit-node (node &optional getter)
254   "Visit NODE using its own getter or GETTER, if non-nil."
255   (elpher-save-pos)
256   (elpher-process-cleanup)
257   (setq elpher-current-node node)
258   (if getter
259       (funcall getter)
260     (let* ((address (elpher-node-address node))
261            (type (if address
262                      (elpher-address-type address)
263                    ?1)))
264       (funcall (car (alist-get type elpher-type-map))))))
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
290 ;;; Buffer preparation
291 ;;
292
293 (defmacro elpher-with-clean-buffer (&rest args)
294   "Evaluate ARGS with a clean *elpher* buffer as current."
295   (list 'with-current-buffer "*elpher*"
296         '(elpher-mode)
297         (append (list 'let '((inhibit-read-only t))
298                       '(erase-buffer))
299                 args)))
300
301
302 ;;; Index rendering
303 ;;
304
305 (defun elpher-insert-index (string)
306   "Insert the index corresponding to STRING into the current buffer."
307   ;; Should be able to split directly on CRLF, but some non-conformant
308   ;; LF-only servers sadly exist, hence the following.
309   (let* ((str-no-period (replace-regexp-in-string "\r\n\.\r\n$" "\r\n" string))
310          (str-no-cr (replace-regexp-in-string "\r" "" str-no-period)))
311     (dolist (line (split-string str-no-cr "\n"))
312       (unless (= (length line) 0)
313         (elpher-insert-index-record line)))))
314
315 (defun elpher-insert-margin (&optional type-name)
316   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
317   (if type-name
318       (progn
319         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
320                         (concat
321                          (propertize "[" 'face 'elpher-margin-brackets)
322                          (propertize type-name 'face 'elpher-margin-key)
323                          (propertize "]" 'face 'elpher-margin-brackets))))
324         (insert " "))
325     (insert (make-string elpher-margin-width ?\s))))
326
327 (defun elpher-node-button-help (node)
328   "Return a string containing the help text for a button corresponding to NODE."
329   (let ((address (elpher-node-address node)))
330     (if (eq (elpher-address-type address) ?h)
331         (let ((url (cadr (split-string (elpher-address-selector address) "URL:"))))
332           (format "mouse-1, RET: open url '%s'" url))
333       (format "mouse-1, RET: open '%s' on %s port %s"
334               (elpher-address-selector address)
335               (elpher-address-host address)
336               (elpher-address-port address)))))
337
338 (defun elpher-insert-index-record (line)
339   "Insert the index record corresponding to LINE into the current buffer."
340   (let* ((type (elt line 0))
341          (fields (split-string (substring line 1) "\t"))
342          (display-string (elt fields 0))
343          (selector (elt fields 1))
344          (host (elt fields 2))
345          (port (string-to-number (elt fields 3))))
346     (elpher-insert-index-record-helper display-string type selector host port)))
347
348 (defun elpher-insert-index-record-helper (display-string type selector host port)
349   "Helper function to insert an index record into the current buffer.
350 The contents of the record are dictated by TYPE, DISPLAY-STRING, SELECTOR, HOST
351 and PORT.
352
353 This function is essentially the second half of `elpher-insert-index-record',
354 but broken out so that it can be used elsewhere."
355   (let ((address (elpher-make-address type selector host port))
356         (type-map-entry (alist-get type elpher-type-map)))
357     (if type-map-entry
358         (let* ((margin-code (cadr type-map-entry))
359                (face (caddr type-map-entry))
360                (node (elpher-make-node elpher-current-node address)))
361           (elpher-insert-margin margin-code)
362           (insert-text-button display-string
363                               'face face
364                               'elpher-node node
365                               'action #'elpher-click-link
366                               'follow-link t
367                               'help-echo (elpher-node-button-help node)))
368       (pcase type
369         (?i ;; Information
370          (elpher-insert-margin)
371          (insert (propertize
372                   (if elpher-buttonify-urls-in-directories
373                       (elpher-buttonify-urls display-string)
374                     display-string)
375                   'face 'elpher-info)))
376         (other ;; Unknown
377          (elpher-insert-margin (concat (char-to-string type) "?"))
378          (insert (propertize display-string
379                              'face 'elpher-unknown-face)))))
380     (insert "\n")))
381
382 (defun elpher-click-link (button)
383   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
384   (let ((node (button-get button 'elpher-node)))
385     (elpher-visit-node node)))
386
387
388 ;;; Selector retrieval (all kinds)
389 ;;
390
391 (defun elpher-process-cleanup ()
392   "Immediately shut down any extant elpher process."
393   (let ((p (get-process "elpher-process")))
394     (if p (delete-process p))))
395
396 (defvar elpher-selector-string)
397
398 (defun elpher-get-selector (address after)
399   "Retrieve selector specified by ADDRESS, then execute AFTER.
400 The result is stored as a string in the variable â€˜elpher-selector-string’."
401   (setq elpher-selector-string "")
402   (make-network-process
403    :name "elpher-process"
404    :host (elpher-address-host address)
405    :service (elpher-address-port address)
406    :filter (lambda (proc string)
407              (setq elpher-selector-string (concat elpher-selector-string string)))
408    :sentinel after)
409   (process-send-string "elpher-process"
410                        (concat (elpher-address-selector address) "\n")))
411
412 ;; Index retrieval
413
414 (defun elpher-get-index-node ()
415   "Getter which retrieves the current node contents as an index."
416   (let ((content (elpher-node-content elpher-current-node))
417         (address (elpher-node-address elpher-current-node)))
418     (if content
419         (progn
420           (elpher-with-clean-buffer
421            (insert content)
422            (elpher-restore-pos)))
423       (if address
424           (progn
425             (elpher-with-clean-buffer
426              (insert "LOADING DIRECTORY..."))
427             (elpher-get-selector address
428                                   (lambda (proc event)
429                                     (unless (string-prefix-p "deleted" event)
430                                       (elpher-with-clean-buffer
431                                        (elpher-insert-index elpher-selector-string)
432                                        (elpher-restore-pos)
433                                        (elpher-set-node-content elpher-current-node
434                                                                 (buffer-string)))))))
435         (progn
436           (elpher-with-clean-buffer
437            (elpher-insert-index elpher-start-index)
438            (elpher-restore-pos)
439            (elpher-set-node-content elpher-current-node
440                                     (buffer-string))))))))
441
442 ;; Text retrieval
443
444 (defconst elpher-url-regex
445   "\\([a-zA-Z]+\\)://\\([a-zA-Z0-9.\-]+\\)\\(?3::[0-9]+\\)?\\(?4:/[^ \r\n\t(),]*\\)?"
446   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
447
448 (defun elpher-make-node-from-matched-url (parent &optional string)
449   "Convert most recent `elpher-url-regex' match to a node.
450
451 PARENT defines the node to set as the parent to the new node.
452
453 If STRING is non-nil, this is given as an argument to all `match-string'
454 calls, as is necessary if the match is performed by `string-match'."
455   (let ((url (match-string 0 string))
456         (protocol (downcase (match-string 1 string))))
457     (if (string= protocol "gopher")
458         (let* ((host (match-string 2 string))
459                (port (if (> (length (match-string 3 string))  1)
460                          (string-to-number (substring (match-string 3 string) 1))
461                        70))
462                (type-and-selector (match-string 4 string))
463                (type (if (> (length type-and-selector) 1)
464                          (elt type-and-selector 1)
465                        ?1))
466                (selector (if (> (length type-and-selector) 1)
467                              (substring type-and-selector 2)
468                            ""))
469                (address (elpher-make-address type selector host port)))
470           (elpher-make-node elpher-current-node address))
471       (let* ((host (match-string 2 string))
472              (port (if (> (length (match-string 3 string)) 1)
473                        (string-to-number (substring (match-string 3 string) 1))
474                      70))
475              (selector (concat "URL:" url))
476              (address (elpher-make-address type selector host port)))
477         (elpher-make-node elpher-current-node address)))))
478
479
480 (defun elpher-buttonify-urls (string)
481   "Turn substrings which look like urls in STRING into clickable buttons."
482   (with-temp-buffer
483     (insert string)
484     (goto-char (point-min))
485     (while (re-search-forward elpher-url-regex nil t)
486         (let ((node (elpher-make-node-from-matched-url elpher-current-node)))
487           (make-text-button (match-beginning 0)
488                             (match-end 0)
489                             'elpher-node  node
490                             'action #'elpher-click-link
491                             'follow-link t
492                             'help-echo (elpher-node-button-help node))))
493     (buffer-string)))
494
495 (defun elpher-process-text (string)
496   "Remove CRs and trailing period from the gopher text document STRING."
497   (let* ((chopped-str (replace-regexp-in-string "\r\n\.\r\n$" "\r\n" string))
498          (cleaned-str (replace-regexp-in-string "\r" "" chopped-str)))
499     (elpher-buttonify-urls cleaned-str)))
500
501 (defun elpher-get-text-node ()
502   "Getter which retrieves the current node contents as a text document."
503   (let ((content (elpher-node-content elpher-current-node))
504         (address (elpher-node-address elpher-current-node)))
505     (if content
506         (progn
507           (elpher-with-clean-buffer
508            (insert content)
509            (elpher-restore-pos)))
510       (progn
511         (elpher-with-clean-buffer
512          (insert "LOADING TEXT..."))
513         (elpher-get-selector address
514                               (lambda (proc event)
515                                 (unless (string-prefix-p "deleted" event)
516                                   (elpher-with-clean-buffer
517                                    (insert (elpher-process-text elpher-selector-string))
518                                    (elpher-restore-pos)
519                                    (elpher-set-node-content elpher-current-node
520                                                             (buffer-string))))))))))
521
522 ;; Image retrieval
523
524 (defun elpher-get-image-node ()
525   "Getter which retrieves the current node contents as an image to view."
526   (let ((content (elpher-node-content elpher-current-node))
527         (address (elpher-node-address elpher-current-node)))
528     (if content
529         (progn
530           (elpher-with-clean-buffer
531            (insert-image content)
532            (elpher-restore-pos)))
533       (if (display-images-p)
534           (progn
535             (elpher-with-clean-buffer
536              (insert "LOADING IMAGE..."))
537             (elpher-get-selector address
538                                  (lambda (proc event)
539                                    (unless (string-prefix-p "deleted" event)
540                                      (let ((image (create-image
541                                                    (encode-coding-string elpher-selector-string
542                                                                          'no-conversion)
543                                                    nil t)))
544                                        (elpher-with-clean-buffer
545                                         (insert-image image)
546                                         (elpher-restore-pos))
547                                        (if elpher-cache-images
548                                            (elpher-set-node-content elpher-current-node
549                                                                     image)))))))
550         (elpher-get-node-download)))))
551
552 ;; Search retrieval
553
554 (defun elpher-get-search-node ()
555   "Getter which submits a search query to the address of the current node."
556   (let ((content (elpher-node-content elpher-current-node))
557         (address (elpher-node-address elpher-current-node))
558         (aborted t))
559     (if content
560         (progn
561           (elpher-with-clean-buffer
562            (insert content)
563            (elpher-restore-pos))
564           (message "Displaying cached search results.  Reload to perform a new search."))
565       (unwind-protect
566           (let* ((query-string (read-string "Query: "))
567                  (query-selector (concat (elpher-address-selector address) "\t" query-string))
568                  (search-address (elpher-make-address ?1
569                                                       query-selector
570                                                       (elpher-address-host address)
571                                                       (elpher-address-port address))))
572             (setq aborted nil)
573             (elpher-with-clean-buffer
574              (insert "LOADING RESULTS..."))
575             (elpher-get-selector search-address
576                                   (lambda (proc event)
577                                     (unless (string-prefix-p "deleted" event)
578                                       (elpher-with-clean-buffer
579                                        (elpher-insert-index elpher-selector-string))
580                                       (goto-char (point-min))
581                                       (elpher-set-node-content elpher-current-node
582                                                                 (buffer-string))))))
583         (if aborted
584             (elpher-visit-parent-node))))))
585
586 ;; Raw server response retrieval
587
588 (defun elpher-get-node-raw ()
589   "Getter which retrieves the raw server response for the current node."
590   (let* ((content (elpher-node-content elpher-current-node))
591          (address (elpher-node-address elpher-current-node)))
592     (elpher-with-clean-buffer
593      (insert "LOADING RAW SERVER RESPONSE..."))
594     (if address
595         (elpher-get-selector address
596                               (lambda (proc event)
597                                 (unless (string-prefix-p "deleted" event)
598                                   (elpher-with-clean-buffer
599                                    (insert elpher-selector-string)
600                                    (goto-char (point-min))))))
601       (progn
602         (elpher-with-clean-buffer
603          (insert elpher-start-index))
604         (goto-char (point-min)))))
605   (message "Displaying raw server response.  Reload or redraw to return to standard view."))
606  
607 ;; File export retrieval
608
609 (defvar elpher-download-filename)
610
611 (defun elpher-get-node-download ()
612   "Getter which retrieves the current node and writes the result to a file."
613   (let* ((address (elpher-node-address elpher-current-node))
614          (selector (elpher-address-selector address)))
615     (elpher-visit-parent-node) ; Do first in case of non-local exits.
616     (let* ((filename-proposal (file-name-nondirectory selector))
617            (filename (read-file-name "Save file as: "
618                                      nil nil nil
619                                      (if (> (length filename-proposal) 0)
620                                          filename-proposal
621                                        "gopher.file"))))
622       (message "Downloading...")
623       (setq elpher-download-filename filename)
624       (elpher-get-selector address
625                             (lambda (proc event)
626                               (let ((coding-system-for-write 'binary))
627                                 (with-temp-file elpher-download-filename
628                                   (insert elpher-selector-string)
629                                   (message (format "Download complate, saved to file %s."
630                                                    elpher-download-filename)))))))))
631
632 ;; URL retrieval
633
634 (defun elpher-get-url-node ()
635   "Getter which attempts to open the URL specified by the current node."
636   (let* ((address (elpher-node-address elpher-current-node))
637          (selector (elpher-address-selector address)))
638     (elpher-visit-parent-node) ; Do first in case of non-local exits.
639     (let ((url (elt (split-string selector "URL:") 1)))
640       (if elpher-open-urls-with-eww
641           (browse-web url)
642         (browse-url url)))))
643
644 ;; Telnet node connection
645
646 (defun elpher-get-telnet-node ()
647   "Getter which opens a telnet connection to the server specified by the current node."
648   (let* ((address (elpher-node-address elpher-current-node))
649          (host (elpher-address-host address))
650          (port (elpher-address-port address)))
651     (elpher-visit-parent-node)
652     (telnet host port)))
653
654
655 ;;; Bookmarks
656 ;;
657
658 (defun elpher-make-bookmark (display-string address)
659   "Make an elpher bookmark.
660 DISPLAY-STRING determines how the bookmark will appear in the bookmark list.
661
662 TYPE specifies how the entry will be retrieved when selected, and is
663 specified using the standard gopher entry type characters.
664
665 ADDRESS is the address of the entry."
666   (list display-string address))
667   
668 (defun elpher-bookmark-display-string (bookmark)
669   "Get the display string of BOOKMARK."
670   (elt bookmark 0))
671
672 (defun elpher-bookmark-address (bookmark)
673   "Get the address for BOOKMARK."
674   (elt bookmark 1))
675
676 (defun elpher-save-bookmarks (bookmarks)
677   "Record the bookmark list BOOKMARKS to the user's bookmark file.
678 Beware that this completely replaces the existing contents of the file."
679   (with-temp-file (locate-user-emacs-file "elpher-bookmarks")
680     (erase-buffer)
681     (pp bookmarks (current-buffer))))
682
683 (defun elpher-load-bookmarks ()
684   "Get the list of bookmarks from the users's bookmark file."
685   (with-temp-buffer
686     (ignore-errors
687       (insert-file-contents (locate-user-emacs-file "elpher-bookmarks"))
688       (goto-char (point-min))
689       (read (current-buffer)))))
690
691 (defun elpher-add-bookmark (bookmark)
692   "Add BOOKMARK to the saved list of bookmarks."
693   (let ((bookmarks (elpher-load-bookmarks)))
694     (add-to-list 'bookmarks bookmark)
695     (elpher-save-bookmarks bookmarks)))
696
697 (defun elpher-remove-bookmark (bookmark)
698   "Remove BOOKMARK from the saved list of bookmarks."
699   (elpher-save-bookmarks
700    (seq-filter (lambda (this-bookmark)
701                  (not (equal bookmark this-bookmark)))
702                (elpher-load-bookmarks))))
703      
704 (defun elpher-display-bookmarks ()
705   "Display saved bookmark list."
706   (interactive)
707   (elpher-with-clean-buffer
708    (insert "Use 'u' to return to the previous page.\n\n"
709            "---- Bookmark list ----\n\n")
710    (let ((bookmarks (elpher-load-bookmarks)))
711      (if bookmarks
712          (dolist (bookmark bookmarks)
713            (let ((display-string (elpher-bookmark-display-string bookmark))
714                  (address (elpher-bookmark-address bookmark)))
715              (elpher-insert-index-record-helper display-string
716                                                 (elpher-address-type address)
717                                                 (elpher-address-selector address)
718                                                 (elpher-address-host address)
719                                                 (elpher-address-port address))))
720        (insert "No bookmarks found.\n")))
721    (insert "\n-----------------------")
722    (goto-char (point-min))
723    (elpher-next-link)))
724
725 (defun elpher-bookmark-link ()
726   "Bookmark the link at point."
727   (interactive)
728   (let ((button (button-at (point))))
729     (if button
730         (let ((node (button-get button 'elpher-node))
731               (type (button-get button 'elpher-node-type))
732               (label (button-label button)))
733           (if node
734               (progn
735                 (elpher-add-bookmark
736                  (elpher-make-bookmark type
737                                        label
738                                        (elpher-node-address node)))
739                 (message "Bookmarked \"%s\"" label))
740             (error "Can only bookmark gopher links, not general URLs")))
741       (error "No link selected"))))
742
743 (defun elpher-unbookmark-link ()
744   "Remove bookmark for the link at point."
745   (interactive)
746   (let ((button (button-at (point))))
747     (if button
748         (let ((node (button-get button 'elpher-node))
749               (type (button-get button 'elpher-node-type)))
750           (if node
751               (elpher-remove-bookmark
752                (elpher-make-bookmark type
753                                      (button-label button)
754                                      (elpher-node-address node)))
755             (error "Can only bookmark gopher links, not general URLs")))
756       (error "No link selected"))))
757
758 ;;; Interactive navigation procedures
759 ;;
760
761 (defun elpher-next-link ()
762   "Move point to the next link on the current page."
763   (interactive)
764   (forward-button 1))
765
766 (defun elpher-prev-link ()
767   "Move point to the previous link on the current page."
768   (interactive)
769   (backward-button 1))
770
771 (defun elpher-follow-current-link ()
772   "Open the link or url at point."
773   (interactive)
774   (push-button))
775
776 (defun elpher-go ()
777   "Go to a particular gopher site."
778   (interactive)
779   (let ((node
780          (let ((host-or-url (read-string "Gopher host or URL: ")))
781            (if (string-match elpher-url-regex host-or-url)
782                (elpher-make-node-from-matched-url elpher-current-node
783                                                   host-or-url)
784              (let ((selector (read-string "Selector (default none): " nil nil ""))
785                    (port (string-to-number (read-string "Port (default 70): "
786                                                         nil nil 70))))
787                (elpher-make-node elpher-current-node
788                                  (elpher-make-address ?1 selector host-or-url port)))))))
789     (switch-to-buffer "*elpher*")
790     (elpher-visit-node node)))
791
792 (defun  elpher-redraw ()
793   "Redraw current page."
794   (interactive)
795   (if elpher-current-node
796       (elpher-visit-node elpher-current-node)
797     (message "No current site.")))
798
799 (defun  elpher-reload ()
800   "Reload current page."
801   (interactive)
802   (if elpher-current-node
803       (elpher-reload-current-node)
804     (message "No current site.")))
805
806 (defun elpher-view-raw ()
807   "View current page as plain text."
808   (interactive)
809   (if elpher-current-node
810       (elpher-visit-node elpher-current-node
811                          #'elpher-get-node-raw)
812     (message "No current site.")))
813
814 (defun elpher-back ()
815   "Go to previous site."
816   (interactive)
817   (if (elpher-node-parent elpher-current-node)
818       (elpher-visit-parent-node)
819     (error "No previous site")))
820
821 (defun elpher-download ()
822   "Download the link at point."
823   (interactive)
824   (let ((button (button-at (point))))
825     (if button
826         (let ((node (button-get button 'elpher-node)))
827           (if node
828               (elpher-visit-node (button-get button 'elpher-node)
829                                  #'elpher-get-node-download)
830             (error "Can only download gopher links, not general URLs")))
831       (error "No link selected"))))
832
833 (defun elpher-build-link-map ()
834   "Build alist mapping link names to destination nodes in current buffer."
835   (let ((link-map nil)
836         (b (next-button (point-min) t)))
837     (while b
838       (add-to-list 'link-map (cons (button-label b) b))
839       (setq b (next-button (button-start b))))
840     link-map))
841
842 (defun elpher-menu ()
843   "Select a directory entry by name.  Similar to the info browser (m)enu command."
844   (interactive)
845   (let* ((link-map (elpher-build-link-map)))
846     (if link-map
847         (let ((key (let ((completion-ignore-case t))
848                      (completing-read "Directory entry/link (tab to autocomplete): "
849                                       link-map nil t))))
850           (if (and key (> (length key) 0))
851               (let ((b (cdr (assoc key link-map))))
852                 (goto-char (button-start b))
853                 (button-activate b)))))))
854
855 (defun elpher-root-dir ()
856   "Visit root of current server."
857   (interactive)
858   (let ((address (elpher-node-address elpher-current-node)))
859     (if address
860         (let ((host (elpher-address-host address))
861               (selector (elpher-address-selector address))
862               (port (elpher-address-port address)))
863           (if (> (length selector) 0)
864               (let ((root-address (elpher-make-address ?1 "" host port)))
865                 (elpher-visit-node (elpher-make-node elpher-current-node
866                                                      root-address)))
867             (error "Already at root directory of current server")))
868       (error "Command invalid for Elpher start page"))))
869
870
871 ;;; Mode and keymap
872 ;;
873
874 (defvar elpher-mode-map
875   (let ((map (make-sparse-keymap)))
876     (define-key map (kbd "TAB") 'elpher-next-link)
877     (define-key map (kbd "<backtab>") 'elpher-prev-link)
878     (define-key map (kbd "u") 'elpher-back)
879     (define-key map (kbd "O") 'elpher-root-dir)
880     (define-key map (kbd "g") 'elpher-go)
881     (define-key map (kbd "r") 'elpher-redraw)
882     (define-key map (kbd "R") 'elpher-reload)
883     (define-key map (kbd "w") 'elpher-view-raw)
884     (define-key map (kbd "d") 'elpher-download)
885     (define-key map (kbd "m") 'elpher-menu)
886     (when (fboundp 'evil-define-key)
887       (evil-define-key 'motion map
888         (kbd "TAB") 'elpher-next-link
889         (kbd "C-]") 'elpher-follow-current-link
890         (kbd "C-t") 'elpher-back
891         (kbd "u") 'elpher-back
892         (kbd "O") 'elpher-root-dir
893         (kbd "g") 'elpher-go
894         (kbd "r") 'elpher-redraw
895         (kbd "R") 'elpher-reload
896         (kbd "w") 'elpher-view-raw
897         (kbd "d") 'elpher-download
898         (kbd "m") 'elpher-menu
899         (kbd "a") 'elpher-bookmark-link
900         (kbd "A") 'elpher-bookmark-current
901         (kbd "x") 'elpher-unbookmark-link
902         (kbd "X") 'elpher-unbookmark-current
903         (kbd "B") 'elpher-display-bookmarks))
904     map)
905   "Keymap for gopher client.")
906
907 (define-derived-mode elpher-mode special-mode "elpher"
908   "Major mode for elpher, an elisp gopher client.")
909
910 (when (fboundp 'evil-set-initial-state)
911   (evil-set-initial-state 'elpher-mode 'motion))
912
913 ;;; Main start procedure
914 ;;
915
916 ;;;###autoload
917 (defun elpher ()
918   "Start elpher with default landing page."
919   (interactive)
920   (if (get-buffer "*elpher*")
921       (switch-to-buffer "*elpher*")
922     (switch-to-buffer "*elpher*")
923     (setq elpher-current-node nil)
924     (let ((start-node (elpher-make-node nil elpher-start-address)))
925       (elpher-visit-node start-node)))
926   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
927
928 ;;; elpher.el ends here