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