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