1 ;;; elpher.el --- A friendly gopher and gemini client -*- lexical-binding: t -*-
3 ;; Copyright (C) 2021 Jens Östlund <jostlund@gmail.com>
4 ;; Copyright (C) 2021 F. Jason Park <jp@neverwas.me>
5 ;; Copyright (C) 2021 Christopher Brannon <chris@the-brannons.com>
6 ;; Copyright (C) 2021 Omar Polo <op@omarpolo.com>
7 ;; Copyright (C) 2021 Noodles! <nnoodle@chiru.no>
8 ;; Copyright (C) 2020-2021 Alex Schroeder <alex@gnu.org>
9 ;; Copyright (C) 2020 Zhiwei Chen <chenzhiwei03@kuaishou.com>
10 ;; Copyright (C) 2020 condy0919 <condy0919@gmail.com>
11 ;; Copyright (C) 2020 Alexis <flexibeast@gmail.com>
12 ;; Copyright (C) 2020 Étienne Deparis <etienne@depar.is>
13 ;; Copyright (C) 2020 Simon Nicolussi <sinic@sinic.name>
14 ;; Copyright (C) 2020 Michel Alexandre Salim <michel@michel-slm.name>
15 ;; Copyright (C) 2020 Koushk Roy <kroy@twilio.com>
16 ;; Copyright (C) 2020 Vee <vee@vnsf.xyz>
17 ;; Copyright (C) 2020 Simon South <simon@simonsouth.net>
18 ;; Copyright (C) 2019-2021 Tim Vaughan <plugd@thelambdalab.xyz>
20 ;; Author: Tim Vaughan <plugd@thelambdalab.xyz>
21 ;; Created: 11 April 2019
23 ;; Keywords: comm gopher
24 ;; Homepage: https://thelambdalab.xyz/elpher
25 ;; Package-Requires: ((emacs "27.1"))
27 ;; This file is not part of GNU Emacs.
29 ;; This program is free software: you can redistribute it and/or modify
30 ;; it under the terms of the GNU General Public License as published by
31 ;; the Free Software Foundation, either version 3 of the License, or
32 ;; (at your option) any later version.
34 ;; This program is distributed in the hope that it will be useful,
35 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
36 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 ;; GNU General Public License for more details.
39 ;; You should have received a copy of the GNU General Public License
40 ;; along with this file. If not, see <http://www.gnu.org/licenses/>.
44 ;; Elpher aims to provide a practical and friendly gopher and gemini
45 ;; client for GNU Emacs. It supports:
47 ;; - intuitive keyboard and mouse-driven browsing,
48 ;; - out-of-the-box compatibility with evil-mode,
49 ;; - clickable web and gopher links *in plain text*,
50 ;; - caching of visited sites,
51 ;; - pleasant and configurable colouring of Gopher directories,
52 ;; - direct visualisation of image files,
53 ;; - gopher connections using TLS encryption,
54 ;; - the fledgling Gemini protocol,
55 ;; - the greybeard Finger protocol.
57 ;; To launch Elpher, simply use 'M-x elpher'. This will open a start
58 ;; page containing information on key bindings and suggested starting
59 ;; points for your gopher exploration.
61 ;; Full instructions can be found in the Elpher info manual.
63 ;; Elpher is under active development. Any suggestions for
64 ;; improvements are welcome, and can be made on the official
65 ;; project page, gopher://thelambdalab.xyz/elpher, or via the
66 ;; project mailing list at https://lists.sr.ht/~michel-slm/elpher.
85 ;;; ANSI colors or XTerm colors
87 (or (require 'xterm-color nil t)
88 (require 'ansi-color))
90 (defalias 'elpher-color-filter-apply
91 (if (fboundp 'xterm-color-filter)
93 (let ((_xterm-color-render nil))
94 (xterm-color-filter s)))
95 #'ansi-color-filter-apply)
96 "A function to filter out ANSI escape sequences.")
98 (defalias 'elpher-color-apply
99 (if (fboundp 'xterm-color-filter)
102 "A function to apply ANSI escape sequences.")
107 (defconst elpher-version "3.0.0"
108 "Current version of elpher.")
110 (defconst elpher-margin-width 6
111 "Width of left-hand margin used when rendering indicies.")
113 (defconst elpher-type-map
114 '(((gopher ?0) elpher-get-gopher-page elpher-render-text "txt" elpher-text)
115 ((gopher ?1) elpher-get-gopher-page elpher-render-index "/" elpher-index)
116 ((gopher ?4) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
117 ((gopher ?5) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
118 ((gopher ?7) elpher-get-gopher-query-page elpher-render-index "?" elpher-search)
119 ((gopher ?9) elpher-get-gopher-page elpher-render-download "bin" elpher-binary)
120 ((gopher ?g) elpher-get-gopher-page elpher-render-image "img" elpher-image)
121 ((gopher ?p) elpher-get-gopher-page elpher-render-image "img" elpher-image)
122 ((gopher ?I) elpher-get-gopher-page elpher-render-image "img" elpher-image)
123 ((gopher ?d) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
124 ((gopher ?P) elpher-get-gopher-page elpher-render-download "doc" elpher-binary)
125 ((gopher ?s) elpher-get-gopher-page elpher-render-download "snd" elpher-binary)
126 ((gopher ?h) elpher-get-gopher-page elpher-render-html "htm" elpher-html)
127 (gemini elpher-get-gemini-page elpher-render-gemini "gem" elpher-gemini)
128 (finger elpher-get-finger-page elpher-render-text "txt" elpher-text)
129 (telnet elpher-get-telnet-page nil "tel" elpher-telnet)
130 (other-url elpher-get-other-url-page nil "url" elpher-other-url)
131 ((special start) elpher-get-start-page nil "E" elpher-index)
132 ((special history) elpher-get-history-page nil "E" elpher-index)
133 ((special visited-pages) elpher-get-visited-pages-page nil "E" elpher-index))
134 "Association list from types to getters, renderers, margin codes and index faces.")
137 ;;; Declarations to avoid compiler warnings.
141 (defvar bookmark-make-record-function)
142 (declare-function bookmark-store "bookmark")
143 (declare-function org-link-store-props "ol")
144 (declare-function org-link-set-parameters "ol")
145 (defvar thing-at-point-uri-schemes)
146 (defvar mu4e~view-beginning-of-url-regexp))
149 ;;; Customization group
153 "A gopher and gemini client."
154 :group 'applications)
156 ;; General appearance and customizations
158 (defcustom elpher-open-urls-with-eww nil
159 "If non-nil, open URL selectors using eww.
160 Otherwise, use the system browser via the `browse-url' function."
163 (defcustom elpher-use-header t
164 "If non-nil, display current page information in buffer header."
167 (defcustom elpher-auto-disengage-TLS nil
168 "If non-nil, automatically disengage TLS following an unsuccessful connection.
169 While enabling this may seem convenient, it is also potentially
170 dangerous as it allows switching from an encrypted channel back to
171 plain text without user input."
174 (defcustom elpher-connection-timeout 5
175 "Specifies the number of seconds to wait for a network connection to time out."
178 (defcustom elpher-filter-ansi-from-text nil
179 "If non-nil, filter ANSI escape sequences from text.
180 The default behaviour is to use the ansi-color package to interpret these
184 (defcustom elpher-certificate-directory
185 (file-name-as-directory (locate-user-emacs-file "elpher-certificates"))
186 "Specify the name of the directory where client certificates will be stored.
187 These certificates may be used for establishing authenticated TLS connections."
190 (defcustom elpher-openssl-command "openssl"
191 "The command used to launch openssl when generating TLS client certificates."
194 (defcustom elpher-default-url-type "gopher"
195 "Default URL type (i.e. scheme) to assume if not explicitly given."
196 :type '(choice (const "gopher")
199 (defcustom elpher-gemini-TLS-cert-checks nil
200 "If non-nil, verify gemini server TLS certs using the default security level.
201 Otherwise, certificate verification is disabled.
203 This defaults to off because it is standard practice for Gemini servers
204 to use self-signed certificates, meaning that most servers provide what
205 EMACS considers to be an invalid certificate."
208 (defcustom elpher-gemini-max-fill-width 80
209 "Specify the maximum default width (in columns) of text/gemini documents.
210 The actual width used is the minimum of this value and the window width at
211 the time when the text is rendered."
214 (defcustom elpher-gemini-link-string "→ "
215 "Specify the string used to indicate links when rendering gemini maps.
219 (defcustom elpher-gemini-bullet-string "•"
220 "Specify the string used for bullets when rendering gemini maps."
223 (defcustom elpher-ipv4-always nil
224 "If non-nil, elpher will always use IPv4 to establish network connections.
225 This can be useful when browsing from a computer that supports IPv6, because
226 some servers which do not support IPv6 can take a long time to time-out."
229 (defcustom elpher-socks-always nil
230 "If non-nil, elpher will establish network connections over a SOCKS proxy.
231 Otherwise, the SOCKS proxy is only used for connections to onion services."
234 ;; Face customizations
236 (defgroup elpher-faces nil
237 "Elpher face customizations."
240 (defface elpher-index
241 '((t :inherit font-lock-keyword-face))
242 "Face used for directory type directory records.")
246 "Face used for text type directory records.")
249 '((t :inherit default))
250 "Face used for info type directory records.")
252 (defface elpher-image
253 '((t :inherit font-lock-string-face))
254 "Face used for image type directory records.")
256 (defface elpher-search
257 '((t :inherit warning))
258 "Face used for search type directory records.")
261 '((t :inherit font-lock-comment-face))
262 "Face used for html type directory records.")
264 (defface elpher-gemini
265 '((t :inherit font-lock-constant-face))
266 "Face used for Gemini type directory records.")
268 (defface elpher-other-url
269 '((t :inherit font-lock-comment-face))
270 "Face used for other URL type links records.")
272 (defface elpher-telnet
273 '((t :inherit font-lock-function-name-face))
274 "Face used for telnet type directory records.")
276 (defface elpher-binary
277 '((t :inherit font-lock-doc-face))
278 "Face used for binary type directory records.")
280 (defface elpher-unknown
281 '((t :inherit error))
282 "Face used for directory records with unknown/unsupported types.")
284 (defface elpher-margin-key
286 "Face used for directory margin key.")
288 (defface elpher-margin-brackets
289 '((t :inherit shadow))
290 "Face used for brackets around directory margin key.")
292 (defface elpher-gemini-heading1
293 '((t :inherit bold :height 1.8))
294 "Face used for gemini heading level 1.")
296 (defface elpher-gemini-heading2
297 '((t :inherit bold :height 1.5))
298 "Face used for gemini heading level 2.")
300 (defface elpher-gemini-heading3
301 '((t :inherit bold :height 1.2))
302 "Face used for gemini heading level 3.")
304 (defface elpher-gemini-preformatted
305 '((t :inherit fixed-pitch))
306 "Face used for pre-formatted gemini text blocks.")
308 (defface elpher-gemini-quoted
309 '((t :inherit font-lock-doc-face))
310 "Face used for gemini quoted texts.")
317 ;; An elpher "address" object is either a url object or a symbol.
318 ;; Symbol addresses are "special", corresponding to pages generated
319 ;; dynamically for and by elpher. All others represent pages which
320 ;; rely on content retrieved over the network.
322 (defun elpher-address-from-url (url-string)
323 "Create a ADDRESS object corresponding to the given URL-STRING."
324 (let ((data (match-data))) ; Prevent parsing clobbering match data
326 (let ((url (url-generic-parse-url url-string)))
327 (unless (and (not (url-fullness url)) (url-type url))
328 (setf (url-fullness url) t)
329 (unless (url-type url)
330 (setf (url-type url) elpher-default-url-type))
331 (unless (url-host url)
332 (let ((p (split-string (url-filename url) "/" nil nil)))
333 (setf (url-host url) (car p))
334 (setf (url-filename url)
336 (concat "/" (mapconcat #'identity (cdr p) "/"))
338 (when (or (equal "gopher" (url-type url))
339 (equal "gophers" (url-type url)))
341 (when (or (equal (url-filename url) "")
342 (equal (url-filename url) "/"))
343 (setf (url-filename url) "/1")))
344 (when (equal "gemini" (url-type url))
346 (if (equal (url-filename url) "")
347 (setf (url-filename url) "/"))))
348 (elpher-remove-redundant-ports url))
349 (set-match-data data))))
351 (defun elpher-remove-redundant-ports (address)
352 "Remove redundant port specifiers from ADDRESS.
353 Here 'redundant' means that the specified port matches the default
354 for that protocol, eg 70 for gopher."
355 (if (and (not (elpher-address-special-p address))
356 (eq (url-portspec address) ; (url-port) is too slow!
357 (pcase (url-type address)
359 ((or "gopher" "gophers") 70)
362 (setf (url-portspec address) nil))
365 (defun elpher-make-gopher-address (type selector host port &optional tls)
366 "Create an ADDRESS object using gopher directory record attributes.
367 The basic attributes include: TYPE, SELECTOR, HOST and PORT.
368 If the optional attribute TLS is non-nil, the address will be marked as
369 requiring gopher-over-TLS."
371 ((equal type ?i) nil)
372 ((and (equal type ?h)
373 (string-prefix-p "URL:" selector))
374 (elpher-address-from-url (elt (split-string selector "URL:") 1)))
376 (elpher-address-from-url
379 ":" (number-to-string port))))
381 (elpher-address-from-url
382 (concat "gopher" (if tls "s" "")
384 ":" (number-to-string port)
388 (defun elpher-make-special-address (type)
389 "Create an ADDRESS object corresponding to the given special address symbol TYPE."
392 (defun elpher-make-start-page ()
393 "Create the start page."
394 (elpher-make-page "Elpher Start Page"
395 (elpher-make-special-address 'start)))
397 (defun elpher-address-to-url (address)
398 "Get string representation of ADDRESS, or nil if ADDRESS is special."
399 (if (elpher-address-special-p address)
401 (url-encode-url (url-recreate-url address))))
403 (defun elpher-address-type (address)
404 "Retrieve type of ADDRESS object.
405 This is used to determine how to retrieve and render the document the
406 address refers to, via the table `elpher-type-map'."
407 (if (symbolp address)
408 (list 'special address)
409 (let ((protocol (url-type address)))
410 (cond ((or (equal protocol "gopher")
411 (equal protocol "gophers"))
413 (if (member (url-filename address) '("" "/"))
415 (string-to-char (substring (url-filename address) 1)))))
416 ((equal protocol "gemini")
418 ((equal protocol "telnet")
420 ((equal protocol "finger")
424 (defun elpher-address-protocol (address)
425 "Retrieve the transport protocol for ADDRESS. This is nil for special addresses."
426 (if (symbolp address)
430 (defun elpher-address-filename (address)
431 "Retrieve the filename component of ADDRESS.
432 For gopher addresses this is a combination of the selector type and selector."
433 (if (symbolp address)
435 (url-unhex-string (url-filename address))))
437 (defun elpher-address-host (address)
438 "Retrieve host from ADDRESS object."
441 (defun elpher-address-user (address)
442 "Retrieve user from ADDRESS object."
445 (defun elpher-address-port (address)
446 "Retrieve port from ADDRESS object.
447 If no address is defined, returns 0. (This is for compatibility with the URL library.)"
448 (if (symbolp address)
452 (defun elpher-address-special-p (address)
453 "Return non-nil if ADDRESS object is special (e.g. start page page)."
456 (defun elpher-address-gopher-p (address)
457 "Return non-nill if ADDRESS object is a gopher address."
458 (and (not (elpher-address-special-p address))
459 (member (elpher-address-protocol address) '("gopher" "gophers"))))
461 (defun elpher-gopher-address-selector (address)
462 "Retrieve gopher selector from ADDRESS object."
463 (if (member (url-filename address) '("" "/"))
465 (url-unhex-string (substring (url-filename address) 2))))
470 (defvar elpher-content-cache (make-hash-table :test 'equal))
471 (defvar elpher-pos-cache (make-hash-table :test 'equal))
473 (defun elpher-get-cached-content (address)
474 "Retrieve the cached content for ADDRESS, or nil if none exists."
475 (gethash address elpher-content-cache))
477 (defun elpher-cache-content (address content)
478 "Set the content cache for ADDRESS to CONTENT."
479 (puthash address content elpher-content-cache))
481 (defun elpher-get-cached-pos (address)
482 "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
483 (gethash address elpher-pos-cache))
485 (defun elpher-cache-pos (address pos)
486 "Set the cursor position cache for ADDRESS to POS."
487 (puthash address pos elpher-pos-cache))
492 (defun elpher-make-page (display-string address)
493 "Create a page with DISPLAY-STRING and ADDRESS."
494 (list display-string address))
496 (defun elpher-page-display-string (page)
497 "Retrieve the display string corresponding to PAGE."
500 (defun elpher-page-address (page)
501 "Retrieve the address corresponding to PAGE."
504 (defun elpher-page-set-address (page new-address)
505 "Set the address corresponding to PAGE to NEW-ADDRESS."
506 (setcar (cdr page) new-address))
508 (defvar elpher-current-page nil
509 "The current page for this Elpher buffer.")
511 (defvar elpher-history nil
512 "The local history stack for this Elpher buffer.
513 This variable is used by `elpher-back' and
514 `elpher-show-history'.")
516 (defvar elpher-visited-pages nil
517 "The global history for all Elpher buffers.
518 This variable is used by `elpher-show-visited-pages'.")
520 (defun elpher-visit-page (page &optional renderer no-history)
521 "Visit PAGE using its own renderer or RENDERER, if non-nil.
522 Additionally, push PAGE onto the history stack and the list of
523 previously-visited pages,unless NO-HISTORY is non-nil."
525 (elpher-process-cleanup)
527 (unless (equal (elpher-page-address elpher-current-page)
528 (elpher-page-address page))
529 (push elpher-current-page elpher-history)
530 (unless (or (elpher-address-special-p (elpher-page-address page))
531 (and elpher-visited-pages
532 (equal page (car elpher-visited-pages))))
533 (push page elpher-visited-pages))))
534 (setq-local elpher-current-page page)
535 (let* ((address (elpher-page-address page))
536 (type (elpher-address-type address))
537 (type-record (cdr (assoc type elpher-type-map))))
539 (funcall (car type-record)
543 (elpher-visit-previous-page)
545 (`(gopher ,type-char)
546 (error "Unsupported gopher selector type '%c' for '%s'"
547 type-char (elpher-address-to-url address)))
549 (error "Unsupported address type '%S' for '%s'"
550 other (elpher-address-to-url address)))))))
552 (defun elpher-visit-previous-page ()
553 "Visit the previous page in the history."
554 (let ((previous-page (pop elpher-history)))
556 (elpher-visit-page previous-page nil t)
557 (error "No previous page"))))
559 (defun elpher-reload-current-page ()
560 "Reload the current page, discarding any existing cached content."
561 (elpher-cache-content (elpher-page-address elpher-current-page) nil)
562 (elpher-visit-page elpher-current-page))
564 (defun elpher-save-pos ()
565 "Save the current position of point to the current page."
566 (when elpher-current-page
567 (elpher-cache-pos (elpher-page-address elpher-current-page) (point))))
569 (defun elpher-restore-pos ()
570 "Restore the position of point to that cached in the current page."
571 (let ((pos (elpher-get-cached-pos (elpher-page-address elpher-current-page))))
574 (goto-char (point-min)))))
577 ;;; Buffer preparation
580 (defvar elpher-buffer-name "*elpher*"
581 "The default name of the Elpher buffer.")
583 (defun elpher-update-header ()
584 "If `elpher-use-header' is true, display current page info in window header."
585 (if elpher-use-header
586 (let* ((display-string (elpher-page-display-string elpher-current-page))
587 (address (elpher-page-address elpher-current-page))
588 (tls-string (if (and (not (elpher-address-special-p address))
589 (member (elpher-address-protocol address)
590 '("gophers" "gemini")))
593 (header (concat display-string
594 (propertize tls-string 'face 'bold))))
595 (setq header-line-format header))))
597 (defmacro elpher-with-clean-buffer (&rest args)
598 "Evaluate ARGS with a clean *elpher* buffer as current."
599 `(with-current-buffer elpher-buffer-name
600 (unless (eq major-mode 'elpher-mode)
601 ;; avoid resetting buffer-local variables
603 (let ((inhibit-read-only t)
604 (ansi-color-context nil)) ;; clean ansi interpreter state
605 (setq-local network-security-level
606 (default-value 'network-security-level))
608 (elpher-update-header)
611 (defun elpher-buffer-message (string &optional line)
612 "Replace first line in elpher buffer with STRING.
613 If LINE is non-nil, replace that line instead."
614 (with-current-buffer elpher-buffer-name
615 (let ((inhibit-read-only t))
616 (goto-char (point-min))
619 (let ((data (match-data)))
622 (re-search-forward "^.*$")
623 (replace-match string))
624 (set-match-data data))))))
630 (defvar elpher-user-coding-system nil
631 "User-specified coding system to use for decoding text responses.")
633 (defun elpher-decode (string)
634 "Decode STRING using autodetected or user-specified coding system."
635 (decode-coding-string string
636 (if elpher-user-coding-system
637 elpher-user-coding-system
638 (detect-coding-string string t))))
640 (defun elpher-preprocess-text-response (string)
641 "Preprocess text selector response contained in STRING.
642 This involes decoding the character representation, and clearing
643 away CRs and any terminating period."
644 (elpher-decode (replace-regexp-in-string "\n\\.\n$" "\n"
645 (replace-regexp-in-string "\r" "" string))))
648 ;;; Network error reporting
651 (defun elpher-network-error (address error)
652 "Display ERROR message following unsuccessful negotiation with ADDRESS.
653 ERROR can be either an error object or a string."
654 (elpher-with-clean-buffer
655 (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
656 "When attempting to retrieve " (elpher-address-to-url address) ":\n"
657 (if (stringp error) error (error-message-string error)) "\n"
658 (propertize "\n----------------\n\n" 'face 'error)
659 "Press 'u' to return to the previous page.")))
662 ;;; General network communication
665 (defvar elpher-network-timer nil
666 "Timer used for network connections.")
668 (defvar elpher-use-tls nil
669 "If non-nil, use TLS to communicate with gopher servers.")
671 (defvar elpher-client-certificate nil
672 "If non-nil, contains client certificate details to use for TLS connections.")
674 (defun elpher-process-cleanup ()
675 "Immediately shut down any extant elpher process and timers."
676 (let ((p (get-process "elpher-process")))
677 (if p (delete-process p)))
678 (if (timerp elpher-network-timer)
679 (cancel-timer elpher-network-timer)))
681 (defun elpher-get-host-response (address default-port query-string response-processor
682 &optional use-tls force-ipv4)
683 "Generic function for retrieving data from ADDRESS.
685 When ADDRESS lacks a specific port, DEFAULT-PORT is used instead.
686 QUERY-STRING is a string sent to the host specified by ADDRESS to
687 illicet a response. This response is passed as an argument to the
688 function RESPONSE-PROCESSOR.
690 If non-nil, USE-TLS specifies that the connection is to be made over
691 TLS. If set to gemini, the certificate verification will be disabled
692 unless `elpher-gemini-TLS-cert-checks' is non-nil.
694 If non-nil, FORCE-IPV4 causes the network connection to be made over
695 ipv4 only. (The default behaviour when this is not set depends on
696 the host operating system and the local network capabilities.)"
697 (if (and use-tls (not (gnutls-available-p)))
698 (error "Use of TLS requires Emacs to be compiled with GNU TLS support")
699 (unless (< (elpher-address-port address) 65536)
700 (error "Cannot establish network connection: port number > 65536"))
701 (when (and (eq use-tls 'gemini) (not elpher-gemini-TLS-cert-checks))
702 (setq-local network-security-level 'low)
703 (setq-local gnutls-verify-error nil))
705 (let* ((kill-buffer-query-functions nil)
706 (port (elpher-address-port address))
707 (host (elpher-address-host address))
708 (service (if (> port 0) port default-port))
709 (response-string-parts nil)
712 (socks (or elpher-socks-always (string-suffix-p ".onion" host)))
713 (gnutls-params (list :type 'gnutls-x509pki
716 (elpher-get-current-keylist address)))
717 (proc (if socks (socks-open-network-stream "elpher-process" nil host service)
718 (make-network-process :name "elpher-process"
720 :family (and force-ipv4 'ipv4)
726 (cons 'gnutls-x509pki
727 (apply #'gnutls-boot-parameters
729 (timer (run-at-time elpher-connection-timeout nil
731 (elpher-process-cleanup)
733 ; Try again with IPv4
734 ((not (or force-ipv4 socks))
735 (message "Connection timed out. Retrying with IPv4.")
736 (elpher-get-host-response address default-port
741 (not (eq use-tls 'gemini))
742 (or elpher-auto-disengage-TLS
744 "TLS connetion failed. Disable TLS mode and retry? ")))
745 (setq elpher-use-tls nil)
746 (elpher-get-host-response address default-port
751 (elpher-network-error address "Connection time-out.")))))))
752 (setq elpher-network-timer timer)
753 (set-process-coding-system proc 'binary 'binary)
754 (set-process-query-on-exit-flag proc nil)
755 (elpher-buffer-message (concat "Connecting to " host "..."
756 " (press 'u' to abort)"))
757 (set-process-filter proc
758 (lambda (_proc string)
762 (setq bytes-received (+ bytes-received (length string)))
763 (let ((new-hkbytes-received (/ bytes-received 102400)))
764 (when (> new-hkbytes-received hkbytes-received)
765 (setq hkbytes-received new-hkbytes-received)
766 (elpher-buffer-message
768 (number-to-string (/ hkbytes-received 10.0))
771 (setq response-string-parts
772 (cons string response-string-parts))))
773 (set-process-sentinel proc
776 (cancel-timer timer))
777 (condition-case the-error
779 ((string-prefix-p "open" event) ; request URL
780 (elpher-buffer-message
781 (concat "Connected to " host ". Receiving data..."
782 " (press 'u' to abort)"))
783 (let ((inhibit-eol-conversion t))
784 (process-send-string proc query-string)))
785 ((string-prefix-p "deleted" event)) ; do nothing
786 ((and (not response-string-parts)
787 (not (or elpher-ipv4-always force-ipv4 socks)))
788 ; Try again with IPv4
789 (message "Connection failed. Retrying with IPv4.")
790 (elpher-get-host-response address default-port
794 (response-string-parts
795 (elpher-with-clean-buffer
796 (insert "Data received. Rendering..."))
797 (funcall response-processor
798 (apply #'concat (reverse response-string-parts)))
799 (elpher-restore-pos))
801 (error "No response from server")))
803 (elpher-network-error address the-error)))))
805 (if use-tls (apply #'gnutls-negotiate :process proc gnutls-params))
806 (funcall (process-sentinel proc) proc "open\n")))
808 (error "Error initiating connection to server")))))
811 ;;; Client-side TLS Certificate Management
814 (defun elpher-generate-certificate (common-name key-file cert-file &optional temporary)
815 "Generate a key and a self-signed client TLS certificate using openssl.
817 The Common Name field of the certificate is set to COMMON-NAME. The
818 arguments KEY-FILE and CERT-FILE should contain the absolute paths of
819 the key and certificate files to write.
821 If TEMPORARY is non-nil, the certificate will be given an exporation
822 period of one day, and the key and certificate files will be deleted
823 when the certificate is no longer needed for the current session.
825 Otherwise, the certificate will be given a 100 year expiration period
826 and the files will not be deleted.
828 The function returns a list containing the current host name, the
829 temporary flag, and the key and cert file names in the form required
830 by `gnutls-boot-parameters`."
831 (let ((exp-key-file (expand-file-name key-file))
832 (exp-cert-file (expand-file-name cert-file)))
835 (call-process elpher-openssl-command nil nil nil
836 "req" "-x509" "-newkey" "rsa:2048"
837 "-days" (if temporary "1" "36500")
839 "-subj" (concat "/CN=" common-name)
840 "-keyout" exp-key-file
841 "-out" exp-cert-file)
842 (list (elpher-address-host (elpher-page-address elpher-current-page))
843 temporary exp-key-file exp-cert-file))
845 (message "Check that openssl is installed, or customize `elpher-openssl-command`.")
846 (error "Program 'openssl', required for certificate generation, not found")))))
848 (defun elpher-generate-throwaway-certificate ()
849 "Generate and return details of a throwaway certificate.
850 The key and certificate files will be deleted when they are no
851 longer needed for this session."
852 (let* ((file-base (make-temp-name "elpher"))
853 (key-file (concat temporary-file-directory file-base ".key"))
854 (cert-file (concat temporary-file-directory file-base ".crt")))
855 (elpher-generate-certificate file-base key-file cert-file t)))
857 (defun elpher-generate-persistent-certificate (file-base common-name)
858 "Generate and return details of a persistent certificate.
859 The argument FILE-BASE is used as the base for the key and certificate
860 files, while COMMON-NAME specifies the common name field of the
863 The key and certificate files are written to in `elpher-certificate-directory'."
864 (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
865 (cert-file (concat elpher-certificate-directory file-base ".crt")))
866 (elpher-generate-certificate common-name key-file cert-file)))
868 (defun elpher-get-existing-certificate (file-base)
869 "Return a certificate object corresponding to an existing certificate.
870 It is assumed that the key files FILE-BASE.key and FILE-BASE.crt exist in
871 the directory `elpher-certificate-directory'."
872 (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
873 (cert-file (concat elpher-certificate-directory file-base ".crt")))
874 (list (elpher-address-host (elpher-page-address elpher-current-page))
876 (expand-file-name key-file)
877 (expand-file-name cert-file))))
879 (defun elpher-install-and-use-existing-certificate (key-file-src cert-file-src file-base)
880 "Install a key+certificate file pair in `elpher-certificate-directory'.
881 The strings KEY-FILE-SRC and CERT-FILE-SRC are the existing key and
882 certificate files to install. The argument FILE-BASE is used as the
883 base for the installed key and certificate files."
884 (let* ((key-file (concat elpher-certificate-directory file-base ".key"))
885 (cert-file (concat elpher-certificate-directory file-base ".crt")))
886 (if (or (file-exists-p key-file)
887 (file-exists-p cert-file))
888 (error "A certificate with base name %s is already installed" file-base))
889 (copy-file key-file-src key-file)
890 (copy-file cert-file-src cert-file)
891 (list (elpher-address-host (elpher-page-address elpher-current-page))
893 (expand-file-name key-file)
894 (expand-file-name cert-file))))
896 (defun elpher-list-existing-certificates ()
897 "Return a list of the persistent certificates in `elpher-certificate-directory'."
898 (unless (file-directory-p elpher-certificate-directory)
899 (make-directory elpher-certificate-directory))
902 (file-name-sans-extension file))
903 (directory-files elpher-certificate-directory nil "\\.key$")))
905 (defun elpher-forget-current-certificate ()
906 "Causes any current certificate to be forgotten.)
907 In the case of throwaway certificates, the key and certificate files
910 (when elpher-client-certificate
911 (unless (and (called-interactively-p 'any)
912 (not (y-or-n-p (concat "Really forget client certificate? "
913 "(Throwaway certificates will be deleted.)"))))
914 (when (cadr elpher-client-certificate)
915 (delete-file (elt elpher-client-certificate 2))
916 (delete-file (elt elpher-client-certificate 3)))
917 (setq elpher-client-certificate nil)
918 (if (called-interactively-p 'any)
919 (message "Client certificate forgotten.")))))
921 (defun elpher-get-current-keylist (address)
922 "Retrieve the `gnutls-boot-parameters'-compatable keylist.
924 This is obtained from the client certificate described by
925 `elpher-current-certificate', if one is available and the host for
926 that certificate matches the host in ADDRESS.
928 If `elpher-current-certificate' is non-nil, and its host name doesn't
929 match that of ADDRESS, the certificate is forgotten."
930 (if elpher-client-certificate
931 (if (string= (car elpher-client-certificate)
932 (elpher-address-host address))
933 (list (cddr elpher-client-certificate))
934 (elpher-forget-current-certificate)
935 (message "Disabling client certificate for new host")
940 ;;; Gopher selector retrieval
943 (defun elpher-get-gopher-response (address renderer)
944 "Get response string from gopher server at ADDRESS and render using RENDERER."
945 (elpher-get-host-response address 70
946 (concat (elpher-gopher-address-selector address) "\r\n")
948 (or (string= (elpher-address-protocol address) "gophers")
951 (defun elpher-get-gopher-page (renderer)
952 "Getter function for gopher pages.
953 The RENDERER procedure is used to display the contents of the page
954 once they are retrieved from the gopher server."
955 (let* ((address (elpher-page-address elpher-current-page))
956 (content (elpher-get-cached-content address)))
957 (if (and content (funcall renderer nil))
958 (elpher-with-clean-buffer
960 (elpher-restore-pos))
961 (elpher-with-clean-buffer
962 (insert "LOADING... (use 'u' to cancel)\n"))
963 (condition-case the-error
964 (elpher-get-gopher-response address renderer)
966 (elpher-network-error address the-error))))))
970 (defun elpher-insert-index (string)
971 "Insert the index corresponding to STRING into the current buffer."
972 ;; Should be able to split directly on CRLF, but some non-conformant
973 ;; LF-only servers sadly exist, hence the following.
974 (let ((str-processed (elpher-preprocess-text-response string)))
975 (dolist (line (split-string str-processed "\n"))
977 (unless (= (length line) 0)
978 (let* ((type (elt line 0))
979 (fields (split-string (substring line 1) "\t"))
980 (display-string (elt fields 0))
981 (selector (elt fields 1))
982 (host (elt fields 2))
983 (port (if (elt fields 3)
984 (string-to-number (elt fields 3))
986 (address (elpher-make-gopher-address type selector host port)))
987 (elpher-insert-index-record display-string address)))))))
989 (defun elpher-insert-margin (&optional type-name)
990 "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
993 (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
995 (propertize "[" 'face 'elpher-margin-brackets)
996 (propertize type-name 'face 'elpher-margin-key)
997 (propertize "]" 'face 'elpher-margin-brackets))))
999 (insert (make-string elpher-margin-width ?\s))))
1001 (defun elpher--page-button-help (_window buffer pos)
1002 "Function called by Emacs to generate mouse-over text.
1003 The arguments specify the BUFFER and the POS within the buffer of the item
1004 for which help is required. The function returns the help to be
1005 displayed. The _WINDOW argument is currently unused."
1006 (with-current-buffer buffer
1007 (let ((button (button-at pos)))
1009 (let* ((page (button-get button 'elpher-page))
1010 (address (elpher-page-address page)))
1011 (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
1013 (elpher-address-to-url address))))))))
1015 (defun elpher-insert-index-record (display-string &optional address)
1016 "Function to insert an index record into the current buffer.
1017 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
1018 If ADDRESS is not supplied or nil the record is rendered as an
1019 'information' line."
1020 (let* ((type (if address (elpher-address-type address) nil))
1021 (type-map-entry (cdr (assoc type elpher-type-map))))
1023 (let* ((margin-code (elt type-map-entry 2))
1024 (face (elt type-map-entry 3))
1025 (filtered-display-string (elpher-color-filter-apply display-string))
1026 (page (elpher-make-page filtered-display-string address)))
1027 (elpher-insert-margin margin-code)
1028 (insert-text-button filtered-display-string
1031 'action #'elpher-click-link
1033 'help-echo #'elpher--page-button-help))
1035 ('nil ;; Information
1036 (elpher-insert-margin)
1037 (let ((propertized-display-string
1038 (propertize display-string 'face 'elpher-info)))
1039 (insert (elpher-process-text-for-display propertized-display-string))))
1040 (`(gopher ,selector-type) ;; Unknown
1041 (elpher-insert-margin (concat (char-to-string selector-type) "?"))
1042 (insert (propertize display-string
1043 'face 'elpher-unknown)))))
1046 (defun elpher-click-link (button)
1047 "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
1048 (let ((page (button-get button 'elpher-page)))
1049 (elpher-visit-page page)))
1051 (defun elpher-render-index (data &optional _mime-type-string)
1052 "Render DATA as an index. MIME-TYPE-STRING is unused."
1053 (elpher-with-clean-buffer
1056 (elpher-insert-index data)
1057 (elpher-cache-content (elpher-page-address elpher-current-page)
1062 (defconst elpher-url-regex
1063 "\\([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_~?/@|#-]\\)?\\)?"
1064 "Regexp used to locate and buttonify URLs in text files loaded by elpher.")
1066 (defun elpher-buttonify-urls (string)
1067 "Turn substrings which look like urls in STRING into clickable buttons."
1070 (goto-char (point-min))
1071 (while (re-search-forward elpher-url-regex nil t)
1072 (let ((page (elpher-make-page (substring-no-properties (match-string 0))
1073 (elpher-address-from-url (match-string 0)))))
1074 (make-text-button (match-beginning 0)
1077 'action #'elpher-click-link
1079 'help-echo #'elpher--page-button-help
1083 (defun elpher-process-text-for-display (string)
1084 "Perform any desired processing of STRING prior to display as text.
1085 Currently includes buttonifying URLs and processing ANSI escape codes."
1086 (elpher-buttonify-urls (if elpher-filter-ansi-from-text
1087 (elpher-color-filter-apply string)
1088 (elpher-color-apply string))))
1090 (defun elpher-render-text (data &optional _mime-type-string)
1091 "Render DATA as text. MIME-TYPE-STRING is unused."
1092 (elpher-with-clean-buffer
1095 (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
1096 (elpher-cache-content
1097 (elpher-page-address elpher-current-page)
1102 (defun elpher-render-image (data &optional _mime-type-string)
1103 "Display DATA as image. MIME-TYPE-STRING is unused."
1106 (if (display-images-p)
1108 (let ((image (create-image
1111 (elpher-with-clean-buffer
1112 (insert-image image)
1113 (elpher-restore-pos))))
1114 (elpher-render-download data))))
1116 ;; Search retrieval and rendering
1118 (defun elpher-get-gopher-query-page (renderer)
1119 "Getter for gopher addresses requiring input.
1120 The response is rendered using the rendering function RENDERER."
1121 (let* ((address (elpher-page-address elpher-current-page))
1122 (content (elpher-get-cached-content address))
1124 (if (and content (funcall renderer nil))
1125 (elpher-with-clean-buffer
1127 (elpher-restore-pos)
1128 (message "Displaying cached search results. Reload to perform a new search."))
1130 (let* ((query-string (read-string "Query: "))
1131 (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
1132 (search-address (elpher-make-gopher-address ?1
1134 (elpher-address-host address)
1135 (elpher-address-port address)
1136 (equal (elpher-address-type address) "gophers"))))
1139 (elpher-with-clean-buffer
1140 (insert "LOADING RESULTS... (use 'u' to cancel)"))
1141 (elpher-get-gopher-response search-address renderer))
1143 (elpher-visit-previous-page))))))
1145 ;; Raw server response rendering
1147 (defun elpher-render-raw (data &optional mime-type-string)
1148 "Display raw DATA in buffer. MIME-TYPE-STRING is also displayed if provided."
1151 (elpher-with-clean-buffer
1152 (when mime-type-string
1153 (insert "MIME type specified by server: '" mime-type-string "'\n"))
1155 (goto-char (point-min)))
1156 (message "Displaying raw server response. Reload or redraw to return to standard view.")))
1158 ;; File save "rendering"
1160 (defun elpher-render-download (data &optional _mime-type-string)
1161 "Save DATA to file. MIME-TYPE-STRING is unused."
1164 (let* ((address (elpher-page-address elpher-current-page))
1165 (selector (if (elpher-address-gopher-p address)
1166 (elpher-gopher-address-selector address)
1167 (elpher-address-filename address))))
1168 (elpher-visit-previous-page) ; Do first in case of non-local exits.
1169 (let* ((filename-proposal (file-name-nondirectory selector))
1170 (filename (read-file-name "Download complete. Save file as: "
1172 (if (> (length filename-proposal) 0)
1175 (let ((coding-system-for-write 'binary))
1176 (with-temp-file filename
1178 (message (format "Saved to file %s." filename))))))
1182 (defun elpher-render-html (data &optional _mime-type-string)
1183 "Render DATA as HTML using shr. MIME-TYPE-STRING is unused."
1184 (elpher-with-clean-buffer
1187 (let ((dom (with-temp-buffer
1189 (libxml-parse-html-region (point-min) (point-max)))))
1190 (shr-insert-document dom)))))
1192 ;; Gemini page retrieval
1194 (defvar elpher-gemini-redirect-chain)
1196 (defun elpher-get-gemini-response (address renderer)
1197 "Get response string from gemini server at ADDRESS and render using RENDERER."
1198 (elpher-get-host-response address 1965
1199 (concat (elpher-address-to-url address) "\r\n")
1200 (lambda (response-string)
1201 (elpher-process-gemini-response response-string renderer))
1204 (defun elpher-parse-gemini-response (response)
1205 "Parse the RESPONSE string and return a list of components.
1206 The list is of the form (code meta body). A response of nil implies
1207 that the response was malformed."
1208 (let ((header-end-idx (string-match "\r\n" response)))
1210 (let ((header (string-trim (substring response 0 header-end-idx)))
1211 (body (substring response (+ header-end-idx 2))))
1212 (if (>= (length header) 2)
1213 (let ((code (substring header 0 2))
1214 (meta (string-trim (substring header 2))))
1215 (list code meta body))
1216 (error "Malformed response: No response status found in header %s" header)))
1217 (error "Malformed response: No CRLF-delimited header found in response %s" response))))
1219 (defun elpher-process-gemini-response (response-string renderer)
1220 "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
1221 (let ((response-components (elpher-parse-gemini-response response-string)))
1222 (let ((response-code (elt response-components 0))
1223 (response-meta (elt response-components 1))
1224 (response-body (elt response-components 2)))
1225 (pcase (elt response-code 0)
1226 (?1 ; Input required
1227 (elpher-with-clean-buffer
1228 (insert "Gemini server is requesting input."))
1229 (let* ((query-string
1230 (if (eq (elt response-code 1) ?1)
1231 (read-passwd (concat response-meta ": "))
1232 (read-string (concat response-meta ": "))))
1233 (query-address (seq-copy (elpher-page-address elpher-current-page)))
1234 (old-fname (url-filename query-address)))
1235 (setf (url-filename query-address)
1236 (concat old-fname "?" (url-build-query-string `((,query-string)))))
1237 (elpher-get-gemini-response query-address renderer)))
1238 (?2 ; Normal response
1239 (funcall renderer response-body response-meta))
1241 (message "Following redirect to %s" response-meta)
1242 (if (>= (length elpher-gemini-redirect-chain) 5)
1243 (error "More than 5 consecutive redirects followed"))
1244 (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
1245 (if (member redirect-address elpher-gemini-redirect-chain)
1246 (error "Redirect loop detected"))
1247 (if (not (string= (elpher-address-protocol redirect-address)
1249 (error "Server tried to automatically redirect to non-gemini URL: %s"
1251 (elpher-page-set-address elpher-current-page redirect-address)
1252 (add-to-list 'elpher-gemini-redirect-chain redirect-address)
1253 (elpher-get-gemini-response redirect-address renderer)))
1254 (?4 ; Temporary failure
1255 (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
1256 response-code response-meta))
1257 (?5 ; Permanent failure
1258 (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
1259 response-code response-meta))
1260 (?6 ; Client certificate required
1261 (elpher-with-clean-buffer
1262 (if elpher-client-certificate
1263 (insert "Gemini server does not recognise the provided TLS certificate:\n\n")
1264 (insert "Gemini server is requesting a valid TLS certificate:\n\n"))
1266 (elpher-gemini-insert-text response-meta))
1267 (let ((chosen-certificate (elpher-choose-client-certificate)))
1268 (unless chosen-certificate
1269 (error "Gemini server requires a client certificate and none was provided"))
1270 (setq elpher-client-certificate chosen-certificate))
1271 (elpher-with-clean-buffer)
1272 (elpher-get-gemini-response (elpher-page-address elpher-current-page) renderer))
1274 (error "Gemini server response unknown: %s %s"
1275 response-code response-meta))))))
1277 (defun elpher--read-answer-polyfill (question answers)
1278 "Polyfill for `read-answer' in Emacs 26.1.
1279 QUESTION is a string containing a question, and ANSWERS
1280 is a list of possible answers."
1281 (completing-read question (mapcar 'identity answers)))
1283 (if (fboundp 'read-answer)
1284 (defalias 'elpher-read-answer 'read-answer)
1285 (defalias 'elpher-read-answer 'elpher--read-answer-polyfill))
1287 (defun elpher-choose-client-certificate ()
1288 "Prompt for a client certificate to use to establish a TLS connection."
1289 (let* ((read-answer-short t))
1290 (pcase (read-answer "What do you want to do? "
1292 "generate and use throw-away certificate")
1294 "generate new or use existing persistent certificate")
1296 "stop immediately")))
1298 (setq elpher-client-certificate (elpher-generate-throwaway-certificate)))
1300 (let* ((existing-certificates (elpher-list-existing-certificates))
1301 (file-base (completing-read
1302 "Nickname for new or existing certificate (autocompletes, empty response aborts): "
1303 existing-certificates)))
1304 (if (string-empty-p (string-trim file-base))
1306 (if (member file-base existing-certificates)
1307 (setq elpher-client-certificate
1308 (elpher-get-existing-certificate file-base))
1309 (pcase (read-answer "Generate new certificate or install externally-generated one? "
1311 "generate new certificate")
1313 "install existing certificate")
1315 "stop immediately")))
1317 (let ((common-name (read-string "Common Name field for new certificate: "
1319 (message "New key and self-signed certificate written to %s"
1320 elpher-certificate-directory)
1321 (elpher-generate-persistent-certificate file-base common-name)))
1323 (let* ((cert-file (read-file-name "Certificate file: " nil nil t))
1324 (key-file (read-file-name "Key file: " nil nil t)))
1325 (message "Key and certificate installed in %s for future use"
1326 elpher-certificate-directory)
1327 (elpher-install-and-use-existing-certificate key-file
1333 (defun elpher-get-gemini-page (renderer)
1334 "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1335 (let* ((address (elpher-page-address elpher-current-page))
1336 (content (elpher-get-cached-content address)))
1337 (condition-case the-error
1338 (if (and content (funcall renderer nil))
1339 (elpher-with-clean-buffer
1341 (elpher-restore-pos))
1342 (elpher-with-clean-buffer
1343 (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1344 (setq elpher-gemini-redirect-chain nil)
1345 (elpher-get-gemini-response address renderer))
1347 (elpher-network-error address the-error)))))
1349 (defun elpher-render-gemini (body &optional mime-type-string)
1350 "Render gemini response BODY with rendering MIME-TYPE-STRING."
1353 (let* ((mime-type-string* (if (or (not mime-type-string)
1354 (string-empty-p mime-type-string))
1355 "text/gemini; charset=utf-8"
1357 (mime-type-split (split-string mime-type-string* ";" t))
1358 (mime-type (string-trim (car mime-type-split)))
1359 (parameters (mapcar (lambda (s)
1360 (let ((key-val (split-string s "=")))
1361 (list (downcase (string-trim (car key-val)))
1362 (downcase (string-trim (cadr key-val))))))
1363 (cdr mime-type-split))))
1364 (when (string-prefix-p "text/" mime-type)
1365 (setq body (decode-coding-string
1367 (if (assoc "charset" parameters)
1368 (intern (cadr (assoc "charset" parameters)))
1370 (setq body (replace-regexp-in-string "\r" "" body)))
1372 ((or "text/gemini" "")
1373 (elpher-render-gemini-map body parameters))
1375 (elpher-render-html body))
1376 ((pred (string-prefix-p "text/"))
1377 (elpher-render-gemini-plain-text body parameters))
1378 ((pred (string-prefix-p "image/"))
1379 (elpher-render-image body))
1381 (elpher-render-download body))))))
1383 (defun elpher-gemini-get-link-url (link-line)
1384 "Extract the url portion of LINK-LINE, a gemini map file link line.
1385 Returns nil in the event that the contents of the line following the
1386 => prefix are empty."
1387 (let ((l (split-string (substring link-line 2))))
1389 (string-trim (elt l 0))
1392 (defun elpher-gemini-get-link-display-string (link-line)
1393 "Extract the display string portion of LINK-LINE, a gemini map file link line.
1394 Returns the url portion in the event that the display-string portion is empty."
1395 (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1396 (idx (string-match "[ \t]" rest)))
1397 (string-trim (if idx
1398 (substring rest (+ idx 1))
1401 (defun elpher-collapse-dot-sequences (filename)
1402 "Collapse dot sequences in FILENAME.
1403 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1404 (let* ((path (split-string filename "/"))
1405 (path-reversed-normalized
1406 (seq-reduce (lambda (a b)
1407 (cond ((and a (equal b "..") (cdr a)))
1408 ((and (not a) (equal b "..")) a) ;leading .. are dropped
1412 (string-join (reverse path-reversed-normalized) "/")))
1414 (defun elpher-address-from-gemini-url (url)
1415 "Extract address from URL with defaults as per gemini map files.
1416 While there's obviously some redundancy here between this function and
1417 `elpher-address-from-url', gemini map file URLs require enough special
1418 treatment that a separate function is warranted."
1419 (let ((address (url-generic-parse-url url))
1420 (current-address (elpher-page-address elpher-current-page)))
1421 (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1422 (setf (url-fullness address) t)
1423 (if (url-host address) ;if there is an explicit host, filenames are absolute
1424 (if (string-empty-p (url-filename address))
1425 (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1426 (setf (url-host address) (url-host current-address))
1427 (setf (url-port address) (url-port current-address))
1428 (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1429 (setf (url-filename address)
1430 (concat (file-name-directory (url-filename current-address))
1431 (url-filename address)))))
1432 (unless (url-type address)
1433 (setf (url-type address) "gemini"))
1434 (when (equal (url-type address) "gemini")
1435 (setf (url-filename address)
1436 (elpher-collapse-dot-sequences (url-filename address)))))
1437 (elpher-remove-redundant-ports address)))
1439 (defun elpher-gemini-insert-link (link-line)
1440 "Insert link described by LINK-LINE into a text/gemini document."
1441 (let* ((url (elpher-gemini-get-link-url link-line))
1442 (display-string (elpher-gemini-get-link-display-string link-line))
1443 (address (elpher-address-from-gemini-url url))
1444 (type (if address (elpher-address-type address) nil))
1445 (type-map-entry (cdr (assoc type elpher-type-map))))
1446 (when display-string
1447 (insert elpher-gemini-link-string)
1449 (let* ((face (elt type-map-entry 3))
1450 (filtered-display-string (elpher-color-filter-apply display-string))
1451 (page (elpher-make-page filtered-display-string address)))
1452 (insert-text-button filtered-display-string
1455 'action #'elpher-click-link
1457 'help-echo #'elpher--page-button-help))
1458 (insert (propertize display-string 'face 'elpher-unknown)))
1462 (defvar elpher--gemini-page-headings nil
1463 "List of headings on the page.")
1465 (defun elpher-gemini-insert-header (header-line)
1466 "Insert header described by HEADER-LINE into a text/gemini document.
1467 The gemini map file line describing the header is given
1469 (when (string-match "^\\(#+\\)[ \t]*" header-line)
1470 (let* ((level (length (match-string 1 header-line)))
1471 (header (substring header-line (match-end 0)))
1473 (1 'elpher-gemini-heading1)
1474 (2 'elpher-gemini-heading2)
1475 (3 'elpher-gemini-heading3)
1477 (fill-column (if (display-graphic-p)
1479 (font-get (font-spec :name (face-font 'default)) :size))
1480 (font-get (font-spec :name (face-font face)) :size)) fill-column)))
1481 (setq elpher--gemini-page-headings (cons (cons header (point))
1482 elpher--gemini-page-headings))
1483 (unless (display-graphic-p)
1484 (insert (make-string level ?#) " "))
1485 (insert (propertize header 'face face))
1488 (defun elpher-gemini-insert-text (text-line)
1489 "Insert a plain non-preformatted TEXT-LINE into a text/gemini document.
1490 This function uses Emacs' auto-fill to wrap text sensibly to a maximum
1491 width defined by `elpher-gemini-max-fill-width'."
1492 (string-match "\\(^[ \t]*\\)\\(\\*[ \t]+\\|>[ \t]*\\)?" text-line)
1493 (let* ((line-prefix (match-string 2 text-line))
1494 (processed-text-line
1496 (cond ((string-prefix-p "*" line-prefix)
1498 (replace-regexp-in-string "\\*"
1499 elpher-gemini-bullet-string
1500 (match-string 0 text-line))
1501 (substring text-line (match-end 0))))
1502 ((string-prefix-p ">" line-prefix)
1503 (propertize text-line 'face 'elpher-gemini-quoted))
1506 (adaptive-fill-mode t)
1507 ;; fill-prefix is important for adaptive-fill-mode: without
1508 ;; it, multi-line list items are not indented correct
1509 (fill-prefix (if (match-string 2 text-line)
1510 (replace-regexp-in-string "[>\*]" " " (match-string 0 text-line))
1512 (insert (elpher-process-text-for-display processed-text-line))
1515 (defun elpher-render-gemini-map (data _parameters)
1516 "Render DATA as a gemini map file, PARAMETERS is currently unused."
1517 (elpher-with-clean-buffer
1518 (setq elpher--gemini-page-headings nil)
1519 (let ((preformatted nil))
1521 (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1522 (dolist (line (split-string data "\n"))
1524 ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1525 (preformatted (insert (elpher-process-text-for-display
1526 (propertize line 'face 'elpher-gemini-preformatted))
1528 ((string-prefix-p "=>" line)
1529 (elpher-gemini-insert-link line))
1530 ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1531 (t (elpher-gemini-insert-text line)))))
1532 (setq elpher--gemini-page-headings (nreverse elpher--gemini-page-headings))
1533 (elpher-cache-content
1534 (elpher-page-address elpher-current-page)
1537 (defun elpher-render-gemini-plain-text (data _parameters)
1538 "Render DATA as plain text file. PARAMETERS is currently unused."
1539 (elpher-with-clean-buffer
1540 (insert (elpher-process-text-for-display data))
1541 (elpher-cache-content
1542 (elpher-page-address elpher-current-page)
1546 ;; Finger page connection
1548 (defun elpher-get-finger-page (renderer)
1549 "Opens a finger connection to the current page address.
1550 The result is rendered using RENDERER."
1551 (let* ((address (elpher-page-address elpher-current-page))
1552 (content (elpher-get-cached-content address)))
1553 (if (and content (funcall renderer nil))
1554 (elpher-with-clean-buffer
1556 (elpher-restore-pos))
1557 (elpher-with-clean-buffer
1558 (insert "LOADING... (use 'u' to cancel)\n"))
1559 (condition-case the-error
1560 (let* ((kill-buffer-query-functions nil)
1561 (user (let ((filename (elpher-address-filename address)))
1562 (if (> (length filename) 1)
1563 (substring filename 1)
1564 (elpher-address-user address)))))
1565 (elpher-get-host-response address 79
1566 (concat user "\r\n")
1569 (elpher-network-error address the-error))))))
1572 ;; Telnet page connection
1574 (defun elpher-get-telnet-page (renderer)
1575 "Opens a telnet connection to the current page address (RENDERER must be nil)."
1577 (elpher-visit-previous-page)
1578 (error "Command not supported for telnet URLs"))
1579 (let* ((address (elpher-page-address elpher-current-page))
1580 (host (elpher-address-host address))
1581 (port (elpher-address-port address)))
1582 (elpher-visit-previous-page)
1588 ;; Other URL page opening
1590 (defun elpher-get-other-url-page (renderer)
1591 "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1593 (elpher-visit-previous-page)
1594 (error "Command not supported for general URLs"))
1595 (let* ((address (elpher-page-address elpher-current-page))
1596 (url (elpher-address-to-url address)))
1598 (elpher-visit-previous-page) ; Do first in case of non-local exits.
1599 (message "Opening URL...")
1600 (if elpher-open-urls-with-eww
1602 (browse-url url)))))
1605 ;; Start page retrieval
1607 (defun elpher-get-start-page (renderer)
1608 "Getter which displays the start page (RENDERER must be nil)."
1610 (elpher-visit-previous-page)
1611 (error "Command not supported for start page"))
1612 (elpher-with-clean-buffer
1613 (insert " --------------------------------------------\n"
1614 " Elpher Gopher and Gemini Client \n"
1615 " version " elpher-version "\n"
1616 " --------------------------------------------\n"
1618 "Default bindings:\n"
1620 " - TAB/Shift-TAB: next/prev item on current page\n"
1621 " - RET/mouse-1: open item under cursor\n"
1622 " - m: select an item on current page by name (autocompletes)\n"
1623 " - u/mouse-3/U: return to previous page or to the start page\n"
1624 " - g: go to a particular address (gopher, gemini, finger)\n"
1625 " - o/O: open a different address selector or the root menu of the current server\n"
1626 " - d/D: download item under cursor or current page\n"
1627 " - i/I: info on item under cursor or current page\n"
1628 " - c/C: copy URL representation of item under cursor or current page\n"
1629 " - a/A: bookmark the item under cursor or current page\n"
1630 " - B: list all bookmarks\n"
1631 " - s/S: show current history stack or all previously visted pages\n"
1632 " - r: redraw current page (using cached contents if available)\n"
1633 " - R: reload current page (regenerates cache)\n"
1634 " - !: set character coding system for gopher (default is to autodetect)\n"
1635 " - T: toggle TLS gopher mode\n"
1636 " - F: forget/discard current TLS client certificate\n"
1637 " - .: display the raw server response for the current page\n"
1639 "Start your exploration of gopher space and gemini:\n")
1640 (elpher-insert-index-record "Floodgap Systems Gopher Server"
1641 (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1642 (elpher-insert-index-record "Project Gemini home page"
1643 (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1645 "Alternatively, select a search engine and enter some search terms:\n")
1646 (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1647 (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1648 (elpher-insert-index-record "Gemini Search Engine (geminispace.info)"
1649 (elpher-address-from-url "gemini://geminispace.info/search"))
1651 "Your bookmarks are stored in your ")
1652 (let ((help-string "RET,mouse-1: Open Emacs bookmark list"))
1653 (insert-text-button "Emacs bookmark list"
1657 (call-interactively #'elpher-open-bookmarks))
1659 'help-echo help-string))
1662 "(Bookmarks from legacy elpher-bookmarks files will be automatically imported.)\n"
1665 "For Elpher release news or to leave feedback, visit:\n")
1666 (elpher-insert-index-record "The Elpher Project Page"
1667 (elpher-make-gopher-address ?1
1673 (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1674 (insert-text-button "Elpher info manual"
1680 'help-echo help-string))
1681 (insert " for the full documentation. **\n")
1683 (concat " (This should be available if you have installed Elpher using\n"
1684 " MELPA. Otherwise you will have to install the manual yourself.)\n")
1686 (elpher-restore-pos)))
1688 ;; History page retrieval
1690 (defun elpher-show-history ()
1691 "Show the current contents of elpher's history stack.
1692 Use \\[elpher-show-visited-pages] to see the entire history.
1693 This is rendered using `elpher-get-history-page' via `elpher-type-map'."
1696 (elpher-make-page "Current History Stack"
1697 (elpher-make-special-address 'history))))
1699 (defun elpher-show-visited-pages ()
1700 "Show the all the pages you've visited using Elpher.
1701 Use \\[elpher-show-history] to see just the current history stack.
1702 This is rendered using `elpher-get-visited-pages-page' via `elpher-type-map'."
1705 (elpher-make-page "Elpher Visted Pages"
1706 (elpher-make-special-address 'visited-pages))))
1708 (defun elpher-get-history-page (renderer)
1709 "Getter which displays the history page (RENDERER must be nil)."
1711 (elpher-visit-previous-page)
1712 (error "Command not supported for history page"))
1713 (elpher-display-history-links elpher-history "Current history stack"))
1715 (defun elpher-get-visited-pages-page (renderer)
1716 "Getter which displays the list of visited pages (RENDERER must be nil)."
1718 (elpher-visit-previous-page)
1719 (error "Command not supported for history page"))
1720 (elpher-display-history-links
1721 (seq-filter (lambda (page)
1722 (not (elpher-address-special-p (elpher-page-address page))))
1723 elpher-visited-pages)
1724 "All visited pages"))
1726 (defun elpher-display-history-links (pages title)
1727 "Show all PAGES in an Elpher buffer with a given TITLE."
1728 (let* ((title-line (concat "---- " title " ----"))
1729 (footer-line (make-string (length title-line) ?-)))
1730 (elpher-with-clean-buffer
1731 (insert title-line "\n\n")
1733 (dolist (page pages)
1735 (let ((display-string (elpher-page-display-string page))
1736 (address (elpher-page-address page)))
1737 (elpher-insert-index-record display-string address))))
1738 (insert "No history items found.\n"))
1739 (insert "\n" footer-line "\n"
1740 "Select and entry or press 'u' to return to the previous page.")
1741 (elpher-restore-pos))))
1746 ;; This code allows Elpher to use the standard Emacs bookmarks: `C-x r
1747 ;; m' to add a bookmark, `C-x r l' to list bookmarks (which is where
1748 ;; you can anotate bookmarks!), `C-x r b' to jump to a bookmark, and
1749 ;; so on. See the Bookmarks section in the Emacs info manual for more.
1751 (defvar elpher-bookmark-link nil
1752 "Prefer bookmarking a link or the current page.
1753 Bind this variable dynamically, or set it to t.
1754 If you set it to t, the commands \\[bookmark-set-no-overwrite]
1755 and \\[elpher-set-bookmark-no-overwrite] do the same thing.")
1757 (defun elpher-bookmark-make-record ()
1758 "Return a bookmark record.
1759 If `elpher-bookmark-link' is non-nil and point is on a link button,
1760 return a bookmark record for that link. Otherwise, return a bookmark
1761 record for the current elpher page."
1762 (let* ((button (and elpher-bookmark-link (button-at (point))))
1764 (button-get button 'elpher-page)
1765 elpher-current-page))
1766 (address (elpher-page-address page))
1767 (url (elpher-address-to-url address))
1768 (display-string (elpher-page-display-string page))
1769 (pos (if button nil (point))))
1770 (if (elpher-address-special-p address)
1771 (error "Cannot bookmark %s" display-string)
1773 (defaults . (,display-string))
1776 (handler . elpher-bookmark-jump)))))
1779 (defun elpher-bookmark-jump (bookmark)
1780 "Go to a particular BOOKMARK."
1781 (let* ((url (cdr (assq 'location bookmark))))
1784 (defun elpher-bookmark-link ()
1785 "Bookmark the link at point.
1786 To bookmark the current page, use \\[elpher-bookmark-current]."
1788 (let ((elpher-bookmark-link t))
1789 (bookmark-set-no-overwrite)))
1791 (defun elpher-bookmark-current ()
1792 "Bookmark the current page.
1793 To bookmark the link at point use \\[elpher-bookmark-link]."
1795 (call-interactively #'bookmark-set-no-overwrite))
1797 (defun elpher-bookmark-import (file)
1798 "Import legacy Elpher bookmarks file FILE into Emacs bookmarks."
1799 (interactive (list (if (and (boundp 'elpher-bookmarks-file)
1800 (file-readable-p elpher-bookmarks-file))
1801 elpher-bookmarks-file
1802 (read-file-name "Old Elpher bookmarks: "
1803 user-emacs-directory nil t
1804 "elpher-bookmarks"))))
1806 (dolist (bookmark (with-temp-buffer
1807 (insert-file-contents file)
1808 (read (current-buffer))))
1809 (let* ((display-string (car bookmark))
1810 (url (cadr bookmark))
1811 (record `(,display-string
1813 (handler . elpher-bookmark-jump))))
1814 (bookmark-store display-string (cdr record) t)))
1817 (defun elpher-open-bookmarks ()
1818 "Display the current list of elpher bookmarks.
1819 This is just a call to `bookmark-bmenu-list', but we also check for a legacy
1820 bookmark file and offer to import it."
1822 (let ((old-bookmarks-file (or (and (boundp 'elpher-bookmarks-file)
1823 elpher-bookmarks-file)
1824 (locate-user-emacs-file "elpher-bookmarks"))))
1825 (when (and (file-readable-p old-bookmarks-file)
1826 (y-or-n-p (concat "Legacy elpher-bookmarks file \""
1828 "\" found. Import now?")))
1829 (elpher-bookmark-import old-bookmarks-file)
1830 (rename-file old-bookmarks-file (concat old-bookmarks-file "-legacy"))))
1831 (call-interactively #'bookmark-bmenu-list))
1839 (defun elpher-org-export-link (link description format protocol)
1840 "Export a LINK with DESCRIPTION for the given PROTOCOL and FORMAT.
1842 FORMAT is an Org export backend. DESCRIPTION may be nil. PROTOCOL may be one
1843 of gemini, gopher or finger."
1844 (let* ((url (if (equal protocol "elpher")
1845 (string-remove-prefix "elpher:" link)
1846 (format "%s:%s" protocol link)))
1847 (desc (or description url)))
1849 (`gemini (format "=> %s %s" url desc))
1850 (`html (format "<a href=\"%s\">%s</a>" url desc))
1851 (`latex (format "\\href{%s}{%s}" url desc))
1852 (_ (if (not description)
1854 (format "%s (%s)" desc url))))))
1856 (defun elpher-org-store-link ()
1857 "Store link to an `elpher' page in Org."
1858 (when (eq major-mode 'elpher-mode)
1859 (let* ((url (elpher-info-current))
1860 (desc (car elpher-current-page))
1862 ((string-prefix-p "gemini:" url) "gemini")
1863 ((string-prefix-p "gopher:" url) "gopher")
1864 ((string-prefix-p "finger:" url) "finger")
1866 (when (equal "elpher" protocol)
1867 ;; Weird link. Or special inner link?
1868 (setq url (concat "elpher:" url)))
1869 (org-link-store-props :type protocol :link url :description desc)
1872 (defun elpher-org-follow-link (link protocol)
1873 "Visit a LINK for the given PROTOCOL.
1875 PROTOCOL may be one of gemini, gopher or finger. This method also
1876 supports the old protocol elpher, where the link is self-contained."
1877 (let ((url (if (equal protocol "elpher")
1878 (string-remove-prefix "elpher:" link)
1879 (format "%s:%s" protocol link))))
1882 (defun elpher-org-mode-integration ()
1883 "Set up `elpher' integration for `org-mode'."
1884 (org-link-set-parameters
1886 :store #'elpher-org-store-link
1887 :export (lambda (link description format _plist)
1888 (elpher-org-export-link link description format "elpher"))
1889 :follow (lambda (link _arg) (elpher-org-follow-link link "elpher")))
1890 (org-link-set-parameters
1892 :export (lambda (link description format _plist)
1893 (elpher-org-export-link link description format "gemini"))
1894 :follow (lambda (link _arg) (elpher-org-follow-link link "gemini")))
1895 (org-link-set-parameters
1897 :export (lambda (link description format _plist)
1898 (elpher-org-export-link link description format "gopher"))
1899 :follow (lambda (link _arg) (elpher-org-follow-link link "gopher")))
1900 (org-link-set-parameters
1902 :export (lambda (link description format _plist)
1903 (elpher-org-export-link link description format "finger"))
1904 :follow (lambda (link _arg) (elpher-org-follow-link link "finger"))))
1906 (add-hook 'org-mode-hook #'elpher-org-mode-integration)
1911 (defun elpher-browse-url-elpher (url &rest _args)
1912 "Browse URL using Elpher. This function is used by `browse-url'."
1913 (interactive (browse-url-interactive-arg "Elpher URL: "))
1916 ;; Use elpher to open gopher, finger and gemini links
1917 ;; For recent version of `browse-url' package
1918 (if (boundp 'browse-url-default-handlers)
1920 'browse-url-default-handlers
1921 '("^\\(gopher\\|finger\\|gemini\\)://" . elpher-browse-url-elpher))
1922 ;; Patch `browse-url-browser-function' for older ones. The value of
1923 ;; that variable is `browse-url-default-browser' by default, so
1924 ;; that's the function that gets advised.
1925 (advice-add browse-url-browser-function :before-while
1926 (lambda (url &rest _args)
1927 "Handle gemini, gopher, and finger schemes using Elpher."
1928 (let ((scheme (downcase (car (split-string url ":" t)))))
1929 (if (member scheme '("gemini" "gopher" "finger"))
1930 ;; `elpher-go' always returns nil, which will stop the
1931 ;; advice chain here in a before-while
1933 ;; chain must continue, then return t.
1936 ;; Register "gemini://" as a URI scheme so `browse-url' does the right thing
1937 (with-eval-after-load 'thingatpt
1938 (add-to-list 'thing-at-point-uri-schemes "gemini://"))
1942 ;; Make mu4e aware of the gemini world
1943 (setq mu4e~view-beginning-of-url-regexp
1944 "\\(?:https?\\|gopher\\|finger\\|gemini\\)://\\|mailto:")
1946 ;;; Interactive procedures
1949 (defun elpher-next-link ()
1950 "Move point to the next link on the current page."
1954 (defun elpher-prev-link ()
1955 "Move point to the previous link on the current page."
1957 (backward-button 1))
1959 (defun elpher-follow-current-link ()
1960 "Open the link or url at point."
1965 (defun elpher-go (host-or-url)
1966 "Go to a particular gopher site HOST-OR-URL.
1967 When run interactively HOST-OR-URL is read from the minibuffer."
1968 (interactive "sGopher or Gemini URL: ")
1969 (let* ((cleaned-host-or-url (string-trim host-or-url))
1970 (address (elpher-address-from-url cleaned-host-or-url))
1971 (page (elpher-make-page cleaned-host-or-url address)))
1972 (switch-to-buffer elpher-buffer-name)
1973 (elpher-with-clean-buffer
1974 (elpher-visit-page page))
1977 (defun elpher-go-current ()
1978 "Go to a particular site read from the minibuffer, initialized with the current URL."
1980 (let ((address (elpher-page-address elpher-current-page)))
1981 (let ((url (read-string "Gopher or Gemini URL: "
1982 (unless (elpher-address-special-p address)
1983 (elpher-address-to-url address)))))
1984 (elpher-visit-page (elpher-make-page url (elpher-address-from-url url))))))
1986 (defun elpher-redraw ()
1987 "Redraw current page."
1989 (elpher-visit-page elpher-current-page))
1991 (defun elpher-reload ()
1992 "Reload current page."
1994 (elpher-reload-current-page))
1996 (defun elpher-toggle-tls ()
1997 "Toggle TLS encryption mode for gopher."
1999 (setq elpher-use-tls (not elpher-use-tls))
2001 (if (gnutls-available-p)
2002 (message "TLS gopher mode enabled. (Will not affect current page until reload.)")
2003 (setq elpher-use-tls nil)
2004 (error "Cannot enable TLS gopher mode: GnuTLS not available"))
2005 (message "TLS gopher mode disabled. (Will not affect current page until reload.)")))
2007 (defun elpher-view-raw ()
2008 "View raw server response for current page."
2010 (if (elpher-address-special-p (elpher-page-address elpher-current-page))
2011 (error "This page was not generated by a server")
2012 (elpher-visit-page elpher-current-page
2013 #'elpher-render-raw)))
2015 (defun elpher-back ()
2016 "Go to previous site."
2018 (elpher-visit-previous-page))
2020 (defun elpher-back-to-start ()
2021 "Go all the way back to the start page."
2023 (setq-local elpher-current-page nil)
2024 (setq-local elpher-history nil)
2025 (elpher-visit-page (elpher-make-start-page)))
2027 (defun elpher-download ()
2028 "Download the link at point."
2030 (let ((button (button-at (point))))
2032 (let ((page (button-get button 'elpher-page)))
2033 (if (elpher-address-special-p (elpher-page-address page))
2034 (error "Cannot download %s"
2035 (elpher-page-display-string page))
2036 (elpher-visit-page (button-get button 'elpher-page)
2037 #'elpher-render-download)))
2038 (error "No link selected"))))
2040 (defun elpher-download-current ()
2041 "Download the current page."
2043 (if (elpher-address-special-p (elpher-page-address elpher-current-page))
2044 (error "Cannot download %s"
2045 (elpher-page-display-string elpher-current-page))
2046 (elpher-visit-page (elpher-make-page
2047 (elpher-page-display-string elpher-current-page)
2048 (elpher-page-address elpher-current-page))
2049 #'elpher-render-download
2052 (defun elpher--build-link-map ()
2053 "Build alist mapping link names to destination pages in current buffer."
2054 (let ((link-map nil)
2055 (b (next-button (point-min) t)))
2057 (push (cons (button-label b) b) link-map)
2058 (setq b (next-button (button-start b))))
2061 (defun elpher-jump ()
2062 "Select a directory entry by name. Similar to the info browser (m)enu command."
2064 (let* ((link-map (elpher--build-link-map)))
2066 (let ((key (let ((completion-ignore-case t))
2067 (completing-read "Directory item/link: "
2069 (if (and key (> (length key) 0))
2070 (let ((b (cdr (assoc key link-map))))
2071 (goto-char (button-start b))
2072 (button-activate b)))))))
2074 (defun elpher-root-dir ()
2075 "Visit root of current server."
2077 (let ((address (elpher-page-address elpher-current-page)))
2078 (if (not (elpher-address-special-p address))
2079 (if (or (member (url-filename address) '("/" ""))
2080 (and (elpher-address-gopher-p address)
2081 (= (length (elpher-gopher-address-selector address)) 0)))
2082 (error "Already at root directory of current server")
2083 (let ((address-copy (elpher-address-from-url
2084 (elpher-address-to-url address))))
2085 (setf (url-filename address-copy) "")
2086 (elpher-go (elpher-address-to-url address-copy))))
2087 (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
2089 (defun elpher-info-page (page)
2090 "Display information on PAGE."
2091 (let ((display-string (elpher-page-display-string page))
2092 (address (elpher-page-address page)))
2093 (if (elpher-address-special-p address)
2094 (message "Special page: %s" display-string)
2095 (message "%s" (elpher-address-to-url address)))))
2097 (defun elpher-info-link ()
2098 "Display information on page corresponding to link at point."
2100 (let ((button (button-at (point))))
2102 (elpher-info-page (button-get button 'elpher-page))
2103 (error "No item selected"))))
2105 (defun elpher-info-current ()
2106 "Display information on current page."
2108 (elpher-info-page elpher-current-page))
2110 (defun elpher-copy-page-url (page)
2111 "Copy URL representation of address of PAGE to `kill-ring'."
2112 (let ((address (elpher-page-address page)))
2113 (if (elpher-address-special-p address)
2114 (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
2115 (let ((url (elpher-address-to-url address)))
2116 (message "Copied \"%s\" to kill-ring/clipboard." url)
2119 (defun elpher-copy-link-url ()
2120 "Copy URL of item at point to `kill-ring'."
2122 (let ((button (button-at (point))))
2124 (elpher-copy-page-url (button-get button 'elpher-page))
2125 (error "No item selected"))))
2127 (defun elpher-copy-current-url ()
2128 "Copy URL of current page to `kill-ring'."
2130 (elpher-copy-page-url elpher-current-page))
2132 (defun elpher-set-gopher-coding-system ()
2133 "Specify an explicit character coding system for gopher selectors."
2135 (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
2136 (setq elpher-user-coding-system system)
2138 (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
2139 (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
2145 (defvar elpher-mode-map
2146 (let ((map (make-sparse-keymap)))
2147 (define-key map (kbd "TAB") 'elpher-next-link)
2148 (define-key map (kbd "<backtab>") 'elpher-prev-link)
2149 (define-key map (kbd "C-M-i") 'elpher-prev-link)
2150 (define-key map (kbd "u") 'elpher-back)
2151 (define-key map (kbd "-") 'elpher-back)
2152 (define-key map (kbd "^") 'elpher-back)
2153 (define-key map [mouse-3] 'elpher-back)
2154 (define-key map (kbd "U") 'elpher-back-to-start)
2155 (define-key map (kbd "g") 'elpher-go)
2156 (define-key map (kbd "o") 'elpher-go-current)
2157 (define-key map (kbd "O") 'elpher-root-dir)
2158 (define-key map (kbd "s") 'elpher-show-history)
2159 (define-key map (kbd "S") 'elpher-show-visited-pages)
2160 (define-key map (kbd "r") 'elpher-redraw)
2161 (define-key map (kbd "R") 'elpher-reload)
2162 (define-key map (kbd "T") 'elpher-toggle-tls)
2163 (define-key map (kbd ".") 'elpher-view-raw)
2164 (define-key map (kbd "d") 'elpher-download)
2165 (define-key map (kbd "D") 'elpher-download-current)
2166 (define-key map (kbd "m") 'elpher-jump)
2167 (define-key map (kbd "i") 'elpher-info-link)
2168 (define-key map (kbd "I") 'elpher-info-current)
2169 (define-key map (kbd "c") 'elpher-copy-link-url)
2170 (define-key map (kbd "C") 'elpher-copy-current-url)
2171 (define-key map (kbd "a") 'elpher-bookmark-link)
2172 (define-key map (kbd "A") 'elpher-bookmark-current)
2173 (define-key map (kbd "B") 'elpher-open-bookmarks)
2174 (define-key map (kbd "!") 'elpher-set-gopher-coding-system)
2175 (define-key map (kbd "F") 'elpher-forget-current-certificate)
2176 (when (fboundp 'evil-define-key*)
2179 (kbd "TAB") 'elpher-next-link
2180 (kbd "C-") 'elpher-follow-current-link
2181 (kbd "C-t") 'elpher-back
2182 (kbd "u") 'elpher-back
2183 (kbd "-") 'elpher-back
2184 (kbd "^") 'elpher-back
2185 [mouse-3] 'elpher-back
2186 (kbd "U") 'elpher-back-to-start
2187 (kbd "g") 'elpher-go
2188 (kbd "o") 'elpher-go-current
2189 (kbd "O") 'elpher-root-dir
2190 (kbd "s") 'elpher-show-history
2191 (kbd "S") 'elpher-show-visited-pages
2192 (kbd "r") 'elpher-redraw
2193 (kbd "R") 'elpher-reload
2194 (kbd "T") 'elpher-toggle-tls
2195 (kbd ".") 'elpher-view-raw
2196 (kbd "d") 'elpher-download
2197 (kbd "D") 'elpher-download-current
2198 (kbd "m") 'elpher-jump
2199 (kbd "i") 'elpher-info-link
2200 (kbd "I") 'elpher-info-current
2201 (kbd "c") 'elpher-copy-link-url
2202 (kbd "C") 'elpher-copy-current-url
2203 (kbd "a") 'elpher-bookmark-link
2204 (kbd "A") 'elpher-bookmark-current
2205 (kbd "B") 'elpher-open-bookmarks
2206 (kbd "!") 'elpher-set-gopher-coding-system
2207 (kbd "F") 'elpher-forget-current-certificate))
2209 "Keymap for gopher client.")
2211 (define-derived-mode elpher-mode special-mode "elpher"
2212 "Major mode for elpher, an elisp gopher client.
2214 This mode is automatically enabled by the interactive
2215 functions which initialize the client, namely
2216 `elpher', and `elpher-go'."
2217 (setq-local elpher--gemini-page-headings nil)
2218 (setq-local elpher-current-page nil)
2219 (setq-local elpher-history nil)
2220 (setq-local elpher-buffer-name (buffer-name))
2221 (setq-local bookmark-make-record-function #'elpher-bookmark-make-record)
2222 (setq-local imenu-create-index-function (lambda () elpher--gemini-page-headings)))
2224 (when (fboundp 'evil-set-initial-state)
2225 (evil-set-initial-state 'elpher-mode 'motion))
2228 ;;; Main start procedure
2232 (defun elpher (&optional arg)
2233 "Start elpher with default landing page.
2234 The buffer used for Elpher sessions is determined by the value of
2235 ‘elpher-buffer-name’. If there is already an Elpher session active in
2236 that buffer, Emacs will simply switch to it. Otherwise, a new session
2237 will begin. A numeric prefix ARG (as in ‘\\[universal-argument] 42
2238 \\[execute-extended-command] elpher RET’) switches to the session with
2239 that number, creating it if necessary. A non numeric prefix ARG means
2240 to create a new session. Returns the buffer selected (or created)."
2242 (let* ((name (default-value 'elpher-buffer-name))
2243 (buf (cond ((numberp arg)
2244 (get-buffer-create (format "%s<%d>" name arg)))
2246 (generate-new-buffer name))
2248 (get-buffer-create name)))))
2249 (pop-to-buffer-same-window buf)
2250 (unless (buffer-modified-p)
2252 (elpher-visit-page (elpher-make-start-page))
2253 "Started Elpher."))); Otherwise (elpher) evaluates to start page string.
2255 ;;; elpher.el ends here