Added ?P and ?s to the list of known item types.
[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.4.5
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 and friendly gopher client
30 ;; for GNU Emacs.  It supports:
31
32 ;; - intuitive keyboard and mouse-driven browsing,
33 ;; - out-of-the-box compatibility with evil-mode,
34 ;; - clickable web and gopher links *in plain text*,
35 ;; - caching of visited sites,
36 ;; - pleasant and configurable colouring of Gopher directories,
37 ;; - direct visualisation of image files,
38 ;; - a simple bookmark management system,
39 ;; - connections using TLS encryption.
40
41 ;; To launch Elpher, simply use 'M-x elpher'.  This will open a start
42 ;; page containing information on key bindings and suggested starting
43 ;; points for your gopher exploration.
44
45 ;; Full instructions can be found in the Elpher info manual.
46
47 ;; Elpher is under active development.  Any suggestions for
48 ;; improvements are welcome!
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.4.5"
61   "Current version of elpher.")
62
63 (defconst elpher-margin-width 6
64   "Width of left-hand margin used when rendering indicies.")
65
66
67 (defconst elpher-type-map
68   '((?0 elpher-get-text-node "txt" elpher-text)
69     (?1 elpher-get-index-node "/" elpher-index)
70     (?4 elpher-get-node-download "bin" elpher-binary)
71     (?5 elpher-get-node-download "bin" elpher-binary)
72     (?7 elpher-get-search-node "?" elpher-search)
73     (?8 elpher-get-telnet-node "tel" elpher-telnet)
74     (?9 elpher-get-node-download "bin" elpher-binary)
75     (?g elpher-get-image-node "img" elpher-image)
76     (?p elpher-get-image-node "img" elpher-image)
77     (?I elpher-get-image-node "img" elpher-image)
78     (?d elpher-get-node-download "doc" elpher-binary)
79     (?P elpher-get-node-download "doc" elpher-binary)
80     (?s elpher-get-node-download "snd" elpher-binary)
81     (?h elpher-get-url-node "url" elpher-url)
82     (bookmarks elpher-get-bookmarks-node "#" elpher-index)
83     (start elpher-get-start-node "#" elpher-index))
84   "Association list from types to getters, margin codes and index faces.")
85
86
87 ;;; Customization group
88 ;;
89
90 (defgroup elpher nil
91   "A gopher client."
92   :group 'applications)
93
94 ;; Face customizations
95
96 (defface elpher-index
97   '((t :inherit font-lock-keyword-face))
98   "Face used for directory type directory records.")
99
100 (defface elpher-text
101   '((t :inherit bold))
102   "Face used for text type directory records.")
103
104 (defface elpher-info
105   '((t :inherit default))
106   "Face used for info type directory records.")
107
108 (defface elpher-image
109   '((t :inherit font-lock-string-face))
110   "Face used for image type directory records.")
111
112 (defface elpher-search
113   '((t :inherit warning))
114   "Face used for search type directory records.")
115
116 (defface elpher-url
117   '((t :inherit font-lock-comment-face))
118   "Face used for url type directory records.")
119
120 (defface elpher-telnet
121   '((t :inherit font-lock-function-name-face))
122   "Face used for telnet type directory records.")
123
124 (defface elpher-binary
125   '((t :inherit font-lock-doc-face))
126   "Face used for binary type directory records.")
127
128 (defface elpher-unknown
129   '((t :inherit error))
130   "Face used for directory records with unknown/unsupported types.")
131
132 (defface elpher-margin-key
133   '((t :inherit bold))
134   "Face used for directory margin key.")
135
136 (defface elpher-margin-brackets
137   '((t :inherit shadow))
138   "Face used for brackets around directory margin key.")
139
140 ;; Other customizations
141
142 (defcustom elpher-open-urls-with-eww nil
143   "If non-nil, open URL selectors using eww.
144 Otherwise, use the system browser via the BROWSE-URL function."
145   :type '(boolean))
146
147 (defcustom elpher-buttonify-urls-in-directories nil
148   "If non-nil, turns URLs matched in directories into clickable buttons."
149   :type '(boolean))
150
151 (defcustom elpher-cache-images nil
152   "If non-nil, cache images in memory in the same way as other content."
153   :type '(boolean))
154
155 (defcustom elpher-use-header t
156   "If non-nil, display current node information in buffer header."
157   :type '(boolean))
158
159 (defcustom elpher-auto-disengage-TLS nil
160   "If non-nil, automatically disengage TLS following an unsuccessful connection.
161 While enabling this may seem convenient, it is also potentially dangerous as it
162 allows switching from an encrypted channel back to plain text without user input."
163   :type '(boolean))
164
165
166 ;;; Model
167 ;;
168
169 ;; Address
170
171 (defun elpher-make-address (type &optional selector host port use-tls)
172   "Create an address of a gopher object with TYPE, SELECTOR, HOST and PORT.
173 Although selector host and port are optional, they are only omitted for
174 special address types, such as 'start for the start page.
175
176 Setting the USE-TLS parameter to non-nil causes Elpher to engage TLS mode
177 before attempting to connect to the server."
178   (if use-tls
179       (list type selector host port 'tls)
180     (list type selector host port)))
181
182 (defun elpher-address-type (address)
183   "Retrieve type from ADDRESS."
184   (elt address 0))
185
186 (defun elpher-address-selector (address)
187   "Retrieve selector from ADDRESS."
188   (elt address 1))
189
190 (defun elpher-address-host (address)
191   "Retrieve host from ADDRESS."
192   (elt address 2))
193
194 (defun elpher-address-port (address)
195   "Retrieve port from ADDRESS."
196   (elt address 3))
197
198 (defun elpher-address-use-tls-p (address)
199   "Return non-nil if ADDRESS is marked as needing TLS."
200   (elt address 4))
201
202 (defun elpher-address-special-p (address)
203   "Return non-nil if ADDRESS is special (e.g. start page, bookmarks page)."
204   (not (elpher-address-host address)))
205
206 ;; Node
207
208 (defun elpher-make-node (display-string address &optional parent)
209   "Create a node in the gopher page hierarchy.
210
211 DISPLAY-STRING records the display string used for the page.
212
213 ADDRESS specifies the address of the gopher page.
214
215 The optional PARENT specifies the parent node in the hierarchy.
216 This is set every time the node is visited, so while it forms
217 an important part of the node data there is no need to set it
218 initially."
219   (list display-string address parent))
220
221 (defun elpher-node-display-string (node)
222   "Retrieve the display string of NODE."
223   (elt node 0))
224
225 (defun elpher-node-address (node)
226   "Retrieve the address of NODE."
227   (elt node 1))
228
229 (defun elpher-node-parent (node)
230   "Retrieve the parent node of NODE."
231   (elt node 2))
232
233 (defun elpher-set-node-parent (node parent)
234   "Set the parent node of NODE to be PARENT."
235   (setcar (cdr (cdr node)) parent))
236
237 ;; Cache
238
239 (defvar elpher-content-cache (make-hash-table :test 'equal))
240 (defvar elpher-pos-cache (make-hash-table :test 'equal))
241
242 (defun elpher-get-cached-content (address)
243   "Retrieve the cached content for ADDRESS, or nil if none exists."
244   (gethash address elpher-content-cache))
245
246 (defun elpher-cache-content (address content)
247   "Set the content cache for ADDRESS to CONTENT."
248   (puthash address content elpher-content-cache))
249
250 (defun elpher-get-cached-pos (address)
251   "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
252   (gethash address elpher-pos-cache))
253
254 (defun elpher-cache-pos (address pos)
255   "Set the cursor position cache for ADDRESS to POS."
256   (puthash address pos elpher-pos-cache))
257
258 ;; Node graph traversal
259
260 (defvar elpher-current-node nil)
261
262 (defun elpher-visit-node (node &optional getter preserve-parent)
263   "Visit NODE using its own getter or GETTER, if non-nil.
264 Additionally, set the parent of NODE to `elpher-current-node',
265 unless PRESERVE-PARENT is non-nil."
266   (elpher-save-pos)
267   (elpher-process-cleanup)
268   (unless preserve-parent
269     (if (and (elpher-node-parent elpher-current-node)
270              (equal (elpher-node-address elpher-current-node)
271                     (elpher-node-address node)))
272         (elpher-set-node-parent node (elpher-node-parent elpher-current-node))
273       (elpher-set-node-parent node elpher-current-node)))
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 nil t))))
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 ;;; Text Processing
324 ;;
325
326 (defvar elpher-user-coding-system nil
327   "User-specified coding system to use for decoding text responses.")
328
329 (defun elpher-decode (string)
330   "Decode STRING using autodetected or user-specified coding system."
331   (decode-coding-string string
332                         (if elpher-user-coding-system
333                             elpher-user-coding-system
334                           (detect-coding-string string t))))
335
336 (defun elpher-preprocess-text-response (string)
337   "Preprocess text selector response contained in STRING.
338 This involes decoding the character representation, and clearing
339 away CRs and any terminating period."
340   (elpher-decode (replace-regexp-in-string "\n\.\n$" "\n"
341                                            (replace-regexp-in-string "\r" "" string))))
342
343 ;;; Index rendering
344 ;;
345
346 (defun elpher-insert-index (string)
347   "Insert the index corresponding to STRING into the current buffer."
348   ;; Should be able to split directly on CRLF, but some non-conformant
349   ;; LF-only servers sadly exist, hence the following.
350   (let ((str-processed (elpher-preprocess-text-response string)))
351     (dolist (line (split-string str-processed "\n"))
352       (unless (= (length line) 0)
353         (let* ((type (elt line 0))
354                (fields (split-string (substring line 1) "\t"))
355                (display-string (elt fields 0))
356                (selector (elt fields 1))
357                (host (elt fields 2))
358                (port (if (elt fields 3)
359                          (string-to-number (elt fields 3))
360                        nil))
361                (address (elpher-make-address type selector host port)))
362           (elpher-insert-index-record display-string address))))))
363
364 (defun elpher-insert-margin (&optional type-name)
365   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
366   (if type-name
367       (progn
368         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
369                         (concat
370                          (propertize "[" 'face 'elpher-margin-brackets)
371                          (propertize type-name 'face 'elpher-margin-key)
372                          (propertize "]" 'face 'elpher-margin-brackets))))
373         (insert " "))
374     (insert (make-string elpher-margin-width ?\s))))
375
376 (defun elpher-node-button-help (node)
377   "Return a string containing the help text for a button corresponding to NODE."
378   (let ((address (elpher-node-address node)))
379     (if (eq (elpher-address-type address) ?h)
380         (let ((url (cadr (split-string (elpher-address-selector address) "URL:"))))
381           (format "mouse-1, RET: open url '%s'" url))
382       (format "mouse-1, RET: open '%s' on %s port %s"
383               (elpher-address-selector address)
384               (elpher-address-host address)
385               (elpher-address-port address)))))
386
387
388 (defun elpher-insert-index-record (display-string address)
389   "Function to insert an index record into the current buffer.
390 The contents of the record are dictated by DISPLAY-STRING and ADDRESS."
391   (let* ((type (elpher-address-type address))
392          (type-map-entry (alist-get type elpher-type-map)))
393     (if type-map-entry
394         (let* ((margin-code (elt type-map-entry 1))
395                (face (elt type-map-entry 2))
396                (node (elpher-make-node display-string address)))
397           (elpher-insert-margin margin-code)
398           (insert-text-button display-string
399                               'face face
400                               'elpher-node node
401                               'action #'elpher-click-link
402                               'follow-link t
403                               'help-echo (elpher-node-button-help node)))
404       (pcase type
405         (?i ;; Information
406          (elpher-insert-margin)
407          (insert (propertize
408                   (if elpher-buttonify-urls-in-directories
409                       (elpher-buttonify-urls display-string)
410                     display-string)
411                   'face 'elpher-info)))
412         (other ;; Unknown
413          (elpher-insert-margin (concat (char-to-string type) "?"))
414          (insert (propertize display-string
415                              'face 'elpher-unknown)))))
416     (insert "\n")))
417
418 (defun elpher-click-link (button)
419   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
420   (let ((node (button-get button 'elpher-node)))
421     (elpher-visit-node node)))
422
423
424 ;;; Selector retrieval (all kinds)
425 ;;
426
427 (defun elpher-process-cleanup ()
428   "Immediately shut down any extant elpher process."
429   (let ((p (get-process "elpher-process")))
430     (if p (delete-process p))))
431
432 (defvar elpher-use-tls nil
433   "If non-nil, use TLS to communicate with gopher servers.")
434
435 (defvar elpher-selector-string)
436
437 (defun elpher-get-selector (address after &optional propagate-error)
438   "Retrieve selector specified by ADDRESS, then execute AFTER.
439 The result is stored as a string in the variable â€˜elpher-selector-string’.
440
441 Usually errors result in an error page being displayed.  This is only
442 appropriate if the selector is to be directly viewed.  If PROPAGATE-ERROR
443 is non-nil, this message is not displayed.  Instead, the error propagates
444 up to the calling function."
445   (setq elpher-selector-string "")
446   (when (elpher-address-use-tls-p address)
447       (if (gnutls-available-p)
448           (when (not elpher-use-tls)
449             (setq elpher-use-tls t)
450             (message "Engaging TLS mode."))
451         (error "Cannot retrieve TLS selector: GnuTLS not available")))
452   (condition-case the-error
453       (let* ((kill-buffer-query-functions nil)
454              (proc (open-network-stream "elpher-process"
455                                        nil
456                                        (elpher-address-host address)
457                                        (elpher-address-port address)
458                                        :type (if elpher-use-tls 'tls 'plain))))
459         (set-process-coding-system proc 'binary)
460         (set-process-filter proc
461                             (lambda (proc string)
462                               (setq elpher-selector-string
463                                     (concat elpher-selector-string string))))
464         (set-process-sentinel proc after)
465         (process-send-string proc
466                              (concat (elpher-address-selector address) "\n")))
467     (error
468      (if (and (consp the-error)
469               (eq (car the-error) 'gnutls-error)
470               (not (elpher-address-use-tls-p address))
471               (or elpher-auto-disengage-TLS
472                   (yes-or-no-p "Could not establish encrypted connection.  Disable TLS mode? ")))
473          (progn
474            (message "Disengaging TLS mode.")
475            (setq elpher-use-tls nil)
476            (elpher-get-selector address after))
477        (elpher-process-cleanup)
478        (if propagate-error
479            (error the-error)
480          (elpher-with-clean-buffer
481           (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
482                   "Failed to connect to " (elpher-get-address-url address) ".\n"
483                   (propertize "\n----------------\n\n" 'face 'error)
484                   "Press 'u' to return to the previous page.")))))))
485
486 ;; Index retrieval
487
488 (defun elpher-get-index-node ()
489   "Getter which retrieves the current node contents as an index."
490   (let* ((address (elpher-node-address elpher-current-node))
491          (content (elpher-get-cached-content address)))
492     (if content
493         (progn
494           (elpher-with-clean-buffer
495            (insert content)
496            (elpher-restore-pos)))
497       (elpher-with-clean-buffer
498        (insert "LOADING DIRECTORY... (use 'u' to cancel)"))
499       (elpher-get-selector address
500                            (lambda (proc event)
501                              (unless (string-prefix-p "deleted" event)
502                                (elpher-with-clean-buffer
503                                 (elpher-insert-index elpher-selector-string)
504                                 (elpher-restore-pos)
505                                 (elpher-cache-content
506                                  (elpher-node-address elpher-current-node)
507                                  (buffer-string)))))))))
508
509 ;; Text retrieval
510
511 (defconst elpher-url-regex
512   "\\([a-zA-Z]+\\)://\\([a-zA-Z0-9.\-]+\\)\\(?3::[0-9]+\\)?\\(?4:/[^ \r\n\t(),]*\\)?"
513   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
514
515 (defun elpher-make-node-from-matched-url (&optional string)
516   "Convert most recent `elpher-url-regex' match to a node.
517
518 If STRING is non-nil, this is given as an argument to all `match-string'
519 calls, as is necessary if the match is performed by `string-match'."
520   (let ((url (match-string 0 string))
521         (protocol (downcase (match-string 1 string))))
522     (if (or (string= protocol "gopher")
523             (string= protocol "gophers"))
524         (let* ((host (match-string 2 string))
525                (port (if (> (length (match-string 3 string))  1)
526                          (string-to-number (substring (match-string 3 string) 1))
527                        70))
528                (type-and-selector (match-string 4 string))
529                (type (if (> (length type-and-selector) 1)
530                          (elt type-and-selector 1)
531                        ?1))
532                (selector (if (> (length type-and-selector) 1)
533                              (substring type-and-selector 2)
534                            ""))
535                (use-tls (string= protocol "gophers"))
536                (address (elpher-make-address type selector host port use-tls)))
537           (elpher-make-node url address))
538       (let* ((host (match-string 2 string))
539              (port (if (> (length (match-string 3 string)) 1)
540                        (string-to-number (substring (match-string 3 string) 1))
541                      70))
542              (selector (concat "URL:" url))
543              (address (elpher-make-address ?h selector host port)))
544         (elpher-make-node url address)))))
545
546
547 (defun elpher-buttonify-urls (string)
548   "Turn substrings which look like urls in STRING into clickable buttons."
549   (with-temp-buffer
550     (insert string)
551     (goto-char (point-min))
552     (while (re-search-forward elpher-url-regex nil t)
553         (let ((node (elpher-make-node-from-matched-url)))
554           (make-text-button (match-beginning 0)
555                             (match-end 0)
556                             'elpher-node  node
557                             'action #'elpher-click-link
558                             'follow-link t
559                             'help-echo (elpher-node-button-help node))))
560     (buffer-string)))
561
562 (defun elpher-get-text-node ()
563   "Getter which retrieves the current node contents as a text document."
564   (let* ((address (elpher-node-address elpher-current-node))
565          (content (elpher-get-cached-content address)))
566     (if content
567         (progn
568           (elpher-with-clean-buffer
569            (insert content)
570            (elpher-restore-pos)))
571       (progn
572         (elpher-with-clean-buffer
573          (insert "LOADING TEXT... (use 'u' to cancel)"))
574         (elpher-get-selector address
575                               (lambda (proc event)
576                                 (unless (string-prefix-p "deleted" event)
577                                   (elpher-with-clean-buffer
578                                    (insert (elpher-buttonify-urls
579                                             (elpher-preprocess-text-response
580                                              elpher-selector-string)))
581                                    (elpher-restore-pos)
582                                    (elpher-cache-content
583                                     (elpher-node-address elpher-current-node)
584                                     (buffer-string))))))))))
585
586 ;; Image retrieval
587
588 (defun elpher-get-image-node ()
589   "Getter which retrieves the current node contents as an image to view."
590   (let* ((address (elpher-node-address elpher-current-node))
591          (content (elpher-get-cached-content address)))
592     (if content
593         (progn
594           (elpher-with-clean-buffer
595            (insert-image content)
596            (elpher-restore-pos)))
597       (if (display-images-p)
598           (progn
599             (elpher-with-clean-buffer
600              (insert "LOADING IMAGE... (use 'u' to cancel)"))
601             (elpher-get-selector address
602                                  (lambda (proc event)
603                                    (unless (string-prefix-p "deleted" event)
604                                      (let ((image (create-image
605                                                    elpher-selector-string
606                                                    nil t)))
607                                        (elpher-with-clean-buffer
608                                         (insert-image image)
609                                         (elpher-restore-pos))
610                                        (if elpher-cache-images
611                                            (elpher-cache-content
612                                             (elpher-node-address elpher-current-node)
613                                             image)))))))
614         (elpher-get-node-download)))))
615
616 ;; Search retrieval
617
618 (defun elpher-get-search-node ()
619   "Getter which submits a search query to the address of the current node."
620   (let* ((address (elpher-node-address elpher-current-node))
621          (content (elpher-get-cached-content address))
622          (aborted t))
623     (if content
624         (progn
625           (elpher-with-clean-buffer
626            (insert content)
627            (elpher-restore-pos))
628           (message "Displaying cached search results.  Reload to perform a new search."))
629       (unwind-protect
630           (let* ((query-string (read-string "Query: "))
631                  (query-selector (concat (elpher-address-selector address) "\t" query-string))
632                  (search-address (elpher-make-address ?1
633                                                       query-selector
634                                                       (elpher-address-host address)
635                                                       (elpher-address-port address))))
636             (setq aborted nil)
637             (elpher-with-clean-buffer
638              (insert "LOADING RESULTS... (use 'u' to cancel)"))
639             (elpher-get-selector search-address
640                                   (lambda (proc event)
641                                     (unless (string-prefix-p "deleted" event)
642                                       (elpher-with-clean-buffer
643                                        (elpher-insert-index elpher-selector-string))
644                                       (goto-char (point-min))
645                                       (elpher-cache-content
646                                        (elpher-node-address elpher-current-node)
647                                        (buffer-string))))))
648         (if aborted
649             (elpher-visit-parent-node))))))
650
651 ;; Raw server response retrieval
652
653 (defun elpher-get-node-raw ()
654   "Getter which retrieves the raw server response for the current node."
655   (let ((address (elpher-node-address elpher-current-node)))
656     (elpher-with-clean-buffer
657      (insert "LOADING RAW SERVER RESPONSE... (use 'u' to cancel)"))
658     (if address
659         (elpher-get-selector address
660                               (lambda (proc event)
661                                 (unless (string-prefix-p "deleted" event)
662                                   (elpher-with-clean-buffer
663                                    (insert elpher-selector-string)
664                                    (goto-char (point-min))))))
665       (progn
666         (elpher-with-clean-buffer
667          (insert elpher-start-index))
668         (goto-char (point-min)))))
669   (message "Displaying raw server response.  Reload or redraw to return to standard view."))
670  
671 ;; File export retrieval
672
673 (defvar elpher-download-filename)
674
675 (defun elpher-get-node-download ()
676   "Getter which retrieves the current node and writes the result to a file."
677   (let* ((address (elpher-node-address elpher-current-node))
678          (selector (elpher-address-selector address)))
679     (elpher-visit-parent-node) ; Do first in case of non-local exits.
680     (let* ((filename-proposal (file-name-nondirectory selector))
681            (filename (read-file-name "Save file as: "
682                                      nil nil nil
683                                      (if (> (length filename-proposal) 0)
684                                          filename-proposal
685                                        "gopher.file"))))
686       (message "Downloading...")
687       (setq elpher-download-filename filename)
688       (condition-case the-error
689           (elpher-get-selector address
690                                (lambda (proc event)
691                                  (let ((coding-system-for-write 'binary))
692                                    (with-temp-file elpher-download-filename
693                                      (insert elpher-selector-string)
694                                      (message (format "Download complate, saved to file %s."
695                                                       elpher-download-filename)))))
696                                t)
697         (error
698          (error "Error downloading %s" elpher-download-filename))))))
699
700 ;; URL retrieval
701
702 (defun elpher-insert-rendered-html (string)
703   "Use shr to insert rendered view of html STRING into current buffer."
704   (let ((dom (with-temp-buffer
705                (insert string)
706                (libxml-parse-html-region (point-min) (point-max)))))
707     (shr-insert-document dom)))
708
709 (defun elpher-get-url-node ()
710   "Getter which attempts to open the URL specified by the current node."
711   (let* ((address (elpher-node-address elpher-current-node))
712          (selector (elpher-address-selector address)))
713     (let ((url (elt (split-string selector "URL:") 1)))
714       (if url
715           (progn
716             (elpher-visit-parent-node) ; Do first in case of non-local exits.
717             (message "Opening URL...")
718             (if elpher-open-urls-with-eww
719                 (browse-web url)
720               (browse-url url)))
721         (let ((content (elpher-get-cached-content address)))
722           (if content
723               (progn
724                 (elpher-with-clean-buffer
725                  (insert content)
726                  (elpher-restore-pos)))
727             (elpher-with-clean-buffer
728              (insert "LOADING HTML... (use 'u' to cancel)"))
729             (elpher-get-selector address
730                                  (lambda (proc event)
731                                    (unless (string-prefix-p "deleted" event)
732                                      (elpher-with-clean-buffer
733                                       (elpher-insert-rendered-html elpher-selector-string)
734                                       (goto-char (point-min))
735                                       (elpher-cache-content
736                                        (elpher-node-address elpher-current-node)
737                                        (buffer-string))))))))))))
738
739 ;; Telnet node connection
740
741 (defun elpher-get-telnet-node ()
742   "Getter which opens a telnet connection to the server specified by the current node."
743   (let* ((address (elpher-node-address elpher-current-node))
744          (host (elpher-address-host address))
745          (port (elpher-address-port address)))
746     (elpher-visit-parent-node)
747     (telnet host port)))
748
749 ;; Start page node retrieval
750
751 (defun elpher-get-start-node ()
752   "Getter which displays the start page."
753   (elpher-with-clean-buffer
754    (insert "     --------------------------------------------\n"
755            "                Elpher Gopher Client             \n"
756            "                   version " elpher-version "\n"
757            "     --------------------------------------------\n"
758            "\n"
759            "Default bindings:\n"
760            "\n"
761            " - TAB/Shift-TAB: next/prev item on current page\n"
762            " - RET/mouse-1: open item under cursor\n"
763            " - m: select an item on current page by name (autocompletes)\n"
764            " - u: return to previous page\n"
765            " - o/O: visit different selector or the root menu of the current server\n"
766            " - g: go to a particular gopher address\n"
767            " - i/I: info on item under cursor or current page\n"
768            " - c/C: copy URL representation of item under cursor or current page\n"
769            " - a/A: bookmark the item under cursor or current page\n"
770            " - x/X: remove bookmark for item under cursor or current page\n"
771            " - B: visit the bookmarks page\n"
772            " - r: redraw current page (using cached contents if available)\n"
773            " - R: reload current page (regenerates cache)\n"
774            " - T: toggle TLS mode\n"
775            " - d/D: download item under cursor or current page\n"
776            " - w: display the raw server response for the current page\n"
777            " - S: set an explicit character coding system (default is to autodetect)\n"
778            "\n"
779            "Start your exploration of gopher space:\n")
780    (elpher-insert-index-record "Floodgap Systems Gopher Server"
781                                (elpher-make-address ?1 "" "gopher.floodgap.com" 70))
782    (insert "\n"
783            "Alternatively, select the following item and enter some search terms:\n")
784    (elpher-insert-index-record "Veronica-2 Gopher Search Engine"
785                                (elpher-make-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
786    (insert "\n"
787            "** Refer to the ")
788    (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
789      (insert-text-button "Elpher info manual"
790                          'face 'link
791                          'action (lambda (button)
792                                    (interactive)
793                                    (info "(elpher)"))
794                          'follow-link t
795                          'help-echo help-string))
796    (insert " for the full documentation. **\n")
797    (insert (propertize
798             (concat "  (This should be available if you have installed Elpher using\n"
799                     "   MELPA. Otherwise you will have to install the manual yourself.)")
800             'face 'shadow))
801    (elpher-restore-pos)))
802
803 ;; Bookmarks page node retrieval
804
805 (defun elpher-get-bookmarks-node ()
806   "Getter to load and display the current bookmark list."
807   (elpher-with-clean-buffer
808    (insert "---- Bookmark list ----\n\n")
809    (let ((bookmarks (elpher-load-bookmarks)))
810      (if bookmarks
811          (dolist (bookmark bookmarks)
812            (let ((display-string (elpher-bookmark-display-string bookmark))
813                  (address (elpher-bookmark-address bookmark)))
814              (elpher-insert-index-record display-string address)))
815        (insert "No bookmarks found.\n")))
816    (insert "\n-----------------------\n\n"
817            "- u: return to previous page\n"
818            "- x: delete selected bookmark\n"
819            "- a: rename selected bookmark\n\n"
820            "Bookmarks are stored in the file "
821            (locate-user-emacs-file "elpher-bookmarks"))
822    (elpher-restore-pos)))
823   
824
825 ;;; Bookmarks
826 ;;
827
828 (defun elpher-make-bookmark (display-string address)
829   "Make an elpher bookmark.
830 DISPLAY-STRING determines how the bookmark will appear in the
831 bookmark list, while ADDRESS is the address of the entry."
832   (list display-string address))
833   
834 (defun elpher-bookmark-display-string (bookmark)
835   "Get the display string of BOOKMARK."
836   (elt bookmark 0))
837
838 (defun elpher-set-bookmark-display-string (bookmark display-string)
839   "Set the display string of BOOKMARK to DISPLAY-STRING."
840   (setcar bookmark display-string))
841
842 (defun elpher-bookmark-address (bookmark)
843   "Get the address for BOOKMARK."
844   (elt bookmark 1))
845
846 (defun elpher-save-bookmarks (bookmarks)
847   "Record the bookmark list BOOKMARKS to the user's bookmark file.
848 Beware that this completely replaces the existing contents of the file."
849   (with-temp-file (locate-user-emacs-file "elpher-bookmarks")
850     (erase-buffer)
851     (insert "; Elpher gopher bookmarks file\n\n"
852             "; Bookmarks are stored as a list of (label (type selector host port))\n"
853             "; s-expressions, where type is stored as a character (i.e. 49 = ?1).\n"
854             "; Feel free to edit by hand, but ensure this structure remains intact.\n\n")
855     (pp bookmarks (current-buffer))))
856
857 (defun elpher-load-bookmarks ()
858   "Get the list of bookmarks from the users's bookmark file."
859   (with-temp-buffer
860     (ignore-errors
861       (insert-file-contents (locate-user-emacs-file "elpher-bookmarks"))
862       (goto-char (point-min))
863       (read (current-buffer)))))
864
865 (defun elpher-add-address-bookmark (address display-string)
866   "Save a bookmark for ADDRESS with label DISPLAY-STRING.
867 If ADDRESS is already bookmarked, update the label only."
868   (let ((bookmarks (elpher-load-bookmarks)))
869     (let ((existing-bookmark (rassoc (list address) bookmarks)))
870       (if existing-bookmark
871           (elpher-set-bookmark-display-string existing-bookmark display-string)
872         (add-to-list 'bookmarks (elpher-make-bookmark display-string address))))
873     (elpher-save-bookmarks bookmarks)))
874
875 (defun elpher-remove-address-bookmark (address)
876   "Remove any bookmark to ADDRESS."
877     (elpher-save-bookmarks
878      (seq-filter (lambda (bookmark)
879                    (not (equal (elpher-bookmark-address bookmark) address)))
880                  (elpher-load-bookmarks))))
881
882 ;;; Interactive procedures
883 ;;
884
885 (defun elpher-next-link ()
886   "Move point to the next link on the current page."
887   (interactive)
888   (forward-button 1))
889
890 (defun elpher-prev-link ()
891   "Move point to the previous link on the current page."
892   (interactive)
893   (backward-button 1))
894
895 (defun elpher-follow-current-link ()
896   "Open the link or url at point."
897   (interactive)
898   (push-button))
899
900 (defun elpher-go ()
901   "Go to a particular gopher site read from the minibuffer.
902 The site may be specified via a URL or explicitly in terms of
903 host, selector and port."
904   (interactive)
905   (let ((node
906          (let ((host-or-url (read-string "Gopher host or URL: ")))
907            (if (string-match elpher-url-regex host-or-url)
908                (elpher-make-node-from-matched-url host-or-url)
909              (let ((selector (read-string "Selector (default none): " nil nil ""))
910                    (port-string (read-string "Port (default 70): " nil nil "70")))
911                (elpher-make-node (concat "gopher://" host-or-url
912                                          ":" port-string
913                                          "/1" selector)
914                                  (elpher-make-address ?1 selector host-or-url
915                                                       (string-to-number port-string))))))))
916     (switch-to-buffer "*elpher*")
917     (elpher-visit-node node)))
918
919 (defun elpher-go-current ()
920   "Go to a particular site read from the minibuffer, initialized with the current URL."
921   (interactive)
922   (let ((address (elpher-node-address elpher-current-node)))
923     (if (elpher-address-special-p address)
924         (error "Command not valid for this page")
925       (let ((url (read-string "URL: " (elpher-get-address-url address))))
926         (if (string-match elpher-url-regex url)
927             (let ((new-node (elpher-make-node-from-matched-url url)))
928               (unless (equal (elpher-node-address new-node) address)
929                 (elpher-visit-node new-node)))
930           (error "Could not parse URL %s" url))))))
931
932 (defun elpher-redraw ()
933   "Redraw current page."
934   (interactive)
935   (if elpher-current-node
936       (elpher-visit-node elpher-current-node)
937     (message "No current site.")))
938
939 (defun elpher-reload ()
940   "Reload current page."
941   (interactive)
942   (if elpher-current-node
943       (elpher-reload-current-node)
944     (message "No current site.")))
945
946 (defun elpher-toggle-tls ()
947   "Toggle TLS encryption mode."
948   (interactive)
949   (setq elpher-use-tls (not elpher-use-tls))
950   (if elpher-use-tls
951       (if (gnutls-available-p)
952           (message "TLS mode enabled.  (Will not affect current page until reload.)")
953         (setq elpher-use-tls nil)
954         (error "Cannot enable TLS mode: GnuTLS not available"))
955     (message "TLS mode disabled.  (Will not affect current page until reload.)")))
956
957 (defun elpher-view-raw ()
958   "View raw server response for current page."
959   (interactive)
960   (if elpher-current-node
961       (if (elpher-address-special-p (elpher-node-address elpher-current-node))
962           (error "This page was not generated by a server")
963         (elpher-visit-node elpher-current-node
964                            #'elpher-get-node-raw))
965     (message "No current site.")))
966
967 (defun elpher-back ()
968   "Go to previous site."
969   (interactive)
970   (if (elpher-node-parent elpher-current-node)
971       (elpher-visit-parent-node)
972     (error "No previous site")))
973
974 (defun elpher-download ()
975   "Download the link at point."
976   (interactive)
977   (let ((button (button-at (point))))
978     (if button
979         (let ((node (button-get button 'elpher-node)))
980           (if (elpher-address-special-p (elpher-node-address node))
981               (error "Cannot download this link")
982             (elpher-visit-node (button-get button 'elpher-node)
983                                #'elpher-get-node-download)))
984       (error "No link selected"))))
985
986 (defun elpher-download-current ()
987   "Download the current page."
988   (interactive)
989   (if (elpher-address-special-p (elpher-node-address elpher-current-node))
990       (error "Cannot download this page")
991     (elpher-visit-node (elpher-make-node
992                         (elpher-node-display-string elpher-current-node)
993                         (elpher-node-address elpher-current-node)
994                         elpher-current-node)
995                        #'elpher-get-node-download
996                        t)))
997
998 (defun elpher-build-link-map ()
999   "Build alist mapping link names to destination nodes in current buffer."
1000   (let ((link-map nil)
1001         (b (next-button (point-min) t)))
1002     (while b
1003       (add-to-list 'link-map (cons (button-label b) b))
1004       (setq b (next-button (button-start b))))
1005     link-map))
1006
1007 (defun elpher-jump ()
1008   "Select a directory entry by name.  Similar to the info browser (m)enu command."
1009   (interactive)
1010   (let* ((link-map (elpher-build-link-map)))
1011     (if link-map
1012         (let ((key (let ((completion-ignore-case t))
1013                      (completing-read "Directory item/link: "
1014                                       link-map nil t))))
1015           (if (and key (> (length key) 0))
1016               (let ((b (cdr (assoc key link-map))))
1017                 (goto-char (button-start b))
1018                 (button-activate b)))))))
1019
1020 (defun elpher-root-dir ()
1021   "Visit root of current server."
1022   (interactive)
1023   (let* ((address (elpher-node-address elpher-current-node))
1024          (host (elpher-address-host address)))
1025     (if host
1026         (let ((host (elpher-address-host address))
1027               (selector (elpher-address-selector address))
1028               (port (elpher-address-port address)))
1029           (if (> (length selector) 0)
1030               (let ((root-address (elpher-make-address ?1 "" host port)))
1031                 (elpher-visit-node
1032                  (elpher-make-node (concat "gopher://" host
1033                                            ":" (number-to-string port)
1034                                            "/1/")
1035                                    root-address)))
1036             (error "Already at root directory of current server")))
1037       (error "Command invalid for this page"))))
1038
1039 (defun elpher-bookmarks-current-p ()
1040   "Return non-nil if current node is a bookmarks page."
1041   (eq (elpher-address-type (elpher-node-address elpher-current-node)) 'bookmarks))
1042
1043 (defun elpher-reload-bookmarks ()
1044   "Reload bookmarks if current node is a bookmarks page."
1045   (if (elpher-bookmarks-current-p)
1046       (elpher-reload-current-node)))
1047
1048 (defun elpher-bookmark-current ()
1049   "Bookmark the current node."
1050   (interactive)
1051   (let ((address (elpher-node-address elpher-current-node))
1052         (display-string (elpher-node-display-string elpher-current-node)))
1053     (if (not (elpher-address-special-p address))
1054         (let ((bookmark-display-string (read-string "Bookmark display string: "
1055                                                     display-string)))
1056           (elpher-add-address-bookmark address bookmark-display-string)
1057           (message "Bookmark added."))
1058       (error "Cannot bookmark %s" display-string))))
1059
1060 (defun elpher-bookmark-link ()
1061   "Bookmark the link at point."
1062   (interactive)
1063   (let ((button (button-at (point))))
1064     (if button
1065         (let* ((node (button-get button 'elpher-node))
1066                (address (elpher-node-address node))
1067                (display-string (elpher-node-display-string node)))
1068           (if (not (elpher-address-special-p address))
1069               (let ((bookmark-display-string (read-string "Bookmark display string: "
1070                                                           display-string)))
1071                 (elpher-add-address-bookmark address bookmark-display-string)
1072                 (elpher-reload-bookmarks)
1073                 (message "Bookmark added."))
1074             (error "Cannot bookmark %s" display-string)))
1075       (error "No link selected"))))
1076
1077 (defun elpher-unbookmark-current ()
1078   "Remove bookmark for the current node."
1079   (interactive)
1080   (let ((address (elpher-node-address elpher-current-node)))
1081     (unless (elpher-address-special-p address)
1082       (elpher-remove-address-bookmark address)
1083       (message "Bookmark removed."))))
1084
1085 (defun elpher-unbookmark-link ()
1086   "Remove bookmark for the link at point."
1087   (interactive)
1088   (let ((button (button-at (point))))
1089     (if button
1090         (let ((node (button-get button 'elpher-node)))
1091           (elpher-remove-address-bookmark (elpher-node-address node))
1092           (elpher-reload-bookmarks)
1093           (message "Bookmark removed."))
1094       (error "No link selected"))))
1095
1096 (defun elpher-bookmarks ()
1097   "Visit bookmarks page."
1098   (interactive)
1099   (switch-to-buffer "*elpher*")
1100   (elpher-visit-node
1101    (elpher-make-node "Bookmarks Page" (elpher-make-address 'bookmarks))))
1102
1103 (defun elpher-info-node (node)
1104   "Display information on NODE."
1105   (let ((display-string (elpher-node-display-string node))
1106         (address (elpher-node-address node)))
1107     (if (not (elpher-address-special-p address))
1108         (message "`%s' on %s port %s"
1109                 (elpher-address-selector address)
1110                 (elpher-address-host address)
1111                 (elpher-address-port address))
1112       (message "%s" display-string))))
1113
1114 (defun elpher-info-link ()
1115   "Display information on node corresponding to link at point."
1116   (interactive)
1117   (let ((button (button-at (point))))
1118     (if button
1119         (elpher-info-node (button-get button 'elpher-node))
1120       (error "No item selected"))))
1121   
1122 (defun elpher-info-current ()
1123   "Display information on current node."
1124   (interactive)
1125   (elpher-info-node elpher-current-node))
1126
1127 (defun elpher-get-address-url (address)
1128   "Get URL representation of ADDRESS."
1129   (let ((type (elpher-address-type address))
1130         (selector (elpher-address-selector address))
1131         (host (elpher-address-host address))
1132         (port (elpher-address-port address)))
1133     (if (and (equal type ?h)
1134              (string-prefix-p "URL:" selector))
1135         (elt (split-string selector "URL:") 1)
1136       (concat "gopher"
1137               (if (elpher-address-use-tls-p address) "s" "")
1138               "://"
1139               host
1140               (if (equal port 70)
1141                   ""
1142                 (format ":%d" port))
1143               "/" (string type)
1144               selector))))
1145
1146 (defun elpher-copy-node-url (node)
1147   "Copy URL representation of address of NODE to `kill-ring'."
1148   (let ((address (elpher-node-address node)))
1149     (if (elpher-address-special-p address)
1150         (error (format "Cannot represent %s as URL" (elpher-node-display-string node)))
1151       (let ((url (elpher-get-address-url address)))
1152         (message "Copied \"%s\" to kill-ring/clipboard." url)
1153         (kill-new url)))))
1154
1155 (defun elpher-copy-link-url ()
1156   "Copy URL of item at point to `kill-ring'."
1157   (interactive)
1158   (let ((button (button-at (point))))
1159     (if button
1160         (elpher-copy-node-url (button-get button 'elpher-node))
1161       (error "No item selected"))))
1162
1163 (defun elpher-copy-current-url ()
1164   "Copy URL of current node to `kill-ring'."
1165   (interactive)
1166   (elpher-copy-node-url elpher-current-node))
1167
1168 (defun elpher-set-coding-system ()
1169   "Specify an explicit character coding system."
1170   (interactive)
1171   (let ((system (read-coding-system "Set coding system to use (default is to autodetect): " nil)))
1172     (setq elpher-user-coding-system system)
1173     (if system
1174         (message "Coding system fixed to %s. (Reload to see effect)." system)
1175       (message "Coding system set to autodetect. (Reload to see effect)."))))
1176
1177 ;;; Mode and keymap
1178 ;;
1179
1180 (defvar elpher-mode-map
1181   (let ((map (make-sparse-keymap)))
1182     (define-key map (kbd "TAB") 'elpher-next-link)
1183     (define-key map (kbd "<backtab>") 'elpher-prev-link)
1184     (define-key map (kbd "u") 'elpher-back)
1185     (define-key map (kbd "O") 'elpher-root-dir)
1186     (define-key map (kbd "g") 'elpher-go)
1187     (define-key map (kbd "o") 'elpher-go-current)
1188     (define-key map (kbd "r") 'elpher-redraw)
1189     (define-key map (kbd "R") 'elpher-reload)
1190     (define-key map (kbd "T") 'elpher-toggle-tls)
1191     (define-key map (kbd "w") 'elpher-view-raw)
1192     (define-key map (kbd "d") 'elpher-download)
1193     (define-key map (kbd "D") 'elpher-download-current)
1194     (define-key map (kbd "m") 'elpher-jump)
1195     (define-key map (kbd "i") 'elpher-info-link)
1196     (define-key map (kbd "I") 'elpher-info-current)
1197     (define-key map (kbd "c") 'elpher-copy-link-url)
1198     (define-key map (kbd "C") 'elpher-copy-current-url)
1199     (define-key map (kbd "a") 'elpher-bookmark-link)
1200     (define-key map (kbd "A") 'elpher-bookmark-current)
1201     (define-key map (kbd "x") 'elpher-unbookmark-link)
1202     (define-key map (kbd "X") 'elpher-unbookmark-current)
1203     (define-key map (kbd "B") 'elpher-bookmarks)
1204     (define-key map (kbd "S") 'elpher-set-coding-system)
1205     (when (fboundp 'evil-define-key)
1206       (evil-define-key 'motion map
1207         (kbd "TAB") 'elpher-next-link
1208         (kbd "C-]") 'elpher-follow-current-link
1209         (kbd "C-t") 'elpher-back
1210         (kbd "u") 'elpher-back
1211         (kbd "O") 'elpher-root-dir
1212         (kbd "g") 'elpher-go
1213         (kbd "o") 'elpher-go-current
1214         (kbd "r") 'elpher-redraw
1215         (kbd "R") 'elpher-reload
1216         (kbd "T") 'elpher-toggle-tls
1217         (kbd "w") 'elpher-view-raw
1218         (kbd "d") 'elpher-download
1219         (kbd "D") 'elpher-download-current
1220         (kbd "m") 'elpher-jump
1221         (kbd "i") 'elpher-info-link
1222         (kbd "I") 'elpher-info-current
1223         (kbd "c") 'elpher-copy-link-url
1224         (kbd "C") 'elpher-copy-current-url
1225         (kbd "a") 'elpher-bookmark-link
1226         (kbd "A") 'elpher-bookmark-current
1227         (kbd "x") 'elpher-unbookmark-link
1228         (kbd "X") 'elpher-unbookmark-current
1229         (kbd "B") 'elpher-bookmarks
1230         (kbd "S") 'elpher-set-coding-system))
1231     map)
1232   "Keymap for gopher client.")
1233
1234 (define-derived-mode elpher-mode special-mode "elpher"
1235   "Major mode for elpher, an elisp gopher client.
1236
1237 This mode is automatically enabled by the interactive
1238 functions which initialize the gopher client, namely
1239 `elpher', `elpher-go' and `elpher-bookmarks'.")
1240
1241 (when (fboundp 'evil-set-initial-state)
1242   (evil-set-initial-state 'elpher-mode 'motion))
1243
1244 ;;; Main start procedure
1245 ;;
1246
1247 ;;;###autoload
1248 (defun elpher ()
1249   "Start elpher with default landing page."
1250   (interactive)
1251   (if (get-buffer "*elpher*")
1252       (switch-to-buffer "*elpher*")
1253     (switch-to-buffer "*elpher*")
1254     (setq elpher-current-node nil)
1255     (let ((start-node (elpher-make-node "Elpher Start Page"
1256                                         (elpher-make-address 'start))))
1257       (elpher-visit-node start-node)))
1258   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
1259
1260 ;;; elpher.el ends here