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