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