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