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