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