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