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