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