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