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