1 ;;; elpher.el --- A friendly gopher and gemini client -*- lexical-binding:t -*-
3 ;; Copyright (C) 2019 Tim Vaughan
5 ;; Author: Tim Vaughan <plugd@thelambdalab.xyz>
6 ;; Created: 11 April 2019
8 ;; Keywords: comm gopher
9 ;; Homepage: http://thelambdalab.xyz/elpher
10 ;; Package-Requires: ((emacs "26"))
12 ;; This file is not part of GNU Emacs.
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.
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.
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/>.
29 ;; Elpher aims to provide a practical and friendly gopher and gemini
30 ;; client for GNU Emacs. It supports:
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.
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.
47 ;; Full instructions can be found in the Elpher info manual.
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/.
73 (defconst elpher-version "2.7.8"
74 "Current version of elpher.")
76 (defconst elpher-margin-width 6
77 "Width of left-hand margin used when rendering indicies.")
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.")
102 ;;; Customization group
107 :group 'applications)
109 ;; General appearance and customizations
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."
116 (defcustom elpher-use-header t
117 "If non-nil, display current page information in buffer header."
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."
126 (defcustom elpher-connection-timeout 5
127 "Specifies the number of seconds to wait for a network connection to time out."
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
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.
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."
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."
151 (defcustom elpher-bookmarks-file (locate-user-emacs-file "elpher-bookmarks")
152 "Specify the name of the file where elpher bookmarks will be saved."
155 ;; Face customizations
157 (defgroup elpher-faces nil
158 "Elpher face customizations."
161 (defface elpher-index
162 '((t :inherit font-lock-keyword-face))
163 "Face used for directory type directory records.")
167 "Face used for text type directory records.")
170 '((t :inherit default))
171 "Face used for info type directory records.")
173 (defface elpher-image
174 '((t :inherit font-lock-string-face))
175 "Face used for image type directory records.")
177 (defface elpher-search
178 '((t :inherit warning))
179 "Face used for search type directory records.")
182 '((t :inherit font-lock-comment-face))
183 "Face used for html type directory records.")
185 (defface elpher-gemini
186 '((t :inherit font-lock-regexp-grouping-backslash))
187 "Face used for Gemini type directory records.")
189 (defface elpher-other-url
190 '((t :inherit font-lock-comment-face))
191 "Face used for other URL type links records.")
193 (defface elpher-telnet
194 '((t :inherit font-lock-function-name-face))
195 "Face used for telnet type directory records.")
197 (defface elpher-binary
198 '((t :inherit font-lock-doc-face))
199 "Face used for binary type directory records.")
201 (defface elpher-unknown
202 '((t :inherit error))
203 "Face used for directory records with unknown/unsupported types.")
205 (defface elpher-margin-key
207 "Face used for directory margin key.")
209 (defface elpher-margin-brackets
210 '((t :inherit shadow))
211 "Face used for brackets around directory margin key.")
213 (defface elpher-gemini-heading1
214 '((t :inherit bold :height 1.8))
215 "Face used for gemini heading level 1.")
217 (defface elpher-gemini-heading2
218 '((t :inherit bold :height 1.5))
219 "Face used for gemini heading level 2.")
221 (defface elpher-gemini-heading3
222 '((t :inherit bold :height 1.2))
223 "Face used for gemini heading level 3.")
225 (defface elpher-gemini-preformatted
226 '((t :inherit fixed-pitch))
227 "Face used for pre-formatted gemini text blocks.")
234 ;; An elpher "address" object is either a url object or a symbol.
235 ;; Symbol addresses are "special", corresponding to pages generated
236 ;; dynamically for and by elpher. All others represent pages which
237 ;; rely on content retrieved over the network.
239 (defun elpher-address-from-url (url-string)
240 "Create a ADDRESS object corresponding to the given URL-STRING."
241 (let ((data (match-data))) ; Prevent parsing clobbering match data
243 (let ((url (url-generic-parse-url url-string)))
244 (unless (and (not (url-fullness url)) (url-type url))
245 (setf (url-fullness url) t)
246 (setf (url-filename url)
247 (url-unhex-string (url-filename url)))
248 (unless (url-type url)
249 (setf (url-type url) "gopher"))
250 (when (or (equal "gopher" (url-type url))
251 (equal "gophers" (url-type url)))
253 (unless (url-host url)
254 (setf (url-host url) (url-filename url))
255 (setf (url-filename url) ""))
256 (when (or (equal (url-filename url) "")
257 (equal (url-filename url) "/"))
258 (setf (url-filename url) "/1")))
259 (when (equal "gemini" (url-type url))
261 (if (equal (url-filename url) "")
262 (setf (url-filename url) "/"))))
264 (set-match-data data))))
266 (defun elpher-make-gopher-address (type selector host port &optional tls)
267 "Create an ADDRESS object using gopher directory record attributes.
268 The basic attributes include: TYPE, SELECTOR, HOST and PORT.
269 If the optional attribute TLS is non-nil, the address will be marked as
270 requiring gopher-over-TLS."
272 ((equal type ?i) nil)
273 ((and (equal type ?h)
274 (string-prefix-p "URL:" selector))
275 (elpher-address-from-url (elt (split-string selector "URL:") 1)))
277 (elpher-address-from-url
280 ":" (number-to-string port))))
282 (elpher-address-from-url
283 (concat "gopher" (if tls "s" "")
285 ":" (number-to-string port)
289 (defun elpher-make-special-address (type)
290 "Create an ADDRESS object corresponding to the given special address symbol TYPE."
293 (defun elpher-address-to-url (address)
294 "Get string representation of ADDRESS, or nil if ADDRESS is special."
295 (if (not (elpher-address-special-p address))
296 (url-encode-url (url-recreate-url address))
299 (defun elpher-address-type (address)
300 "Retrieve type of ADDRESS object.
301 This is used to determine how to retrieve and render the document the
302 address refers to, via the table `elpher-type-map'."
303 (if (symbolp address)
304 (list 'special address)
305 (let ((protocol (url-type address)))
306 (cond ((or (equal protocol "gopher")
307 (equal protocol "gophers"))
309 (if (member (url-filename address) '("" "/"))
311 (string-to-char (substring (url-filename address) 1)))))
312 ((equal protocol "gemini")
314 ((equal protocol "telnet")
316 ((equal protocol "finger")
320 (defun elpher-address-protocol (address)
321 "Retrieve the transport protocol for ADDRESS. This is nil for special addresses."
322 (if (symbolp address)
326 (defun elpher-address-filename (address)
327 "Retrieve the filename component of ADDRESS.
328 For gopher addresses this is a combination of the selector type and selector."
329 (if (symbolp address)
331 (url-filename address)))
333 (defun elpher-address-host (address)
334 "Retrieve host from ADDRESS object."
337 (defun elpher-address-user (address)
338 "Retrieve user from ADDRESS object."
341 (defun elpher-address-port (address)
342 "Retrieve port from ADDRESS object.
343 If no address is defined, returns 0. (This is for compatibility with the URL library.)"
344 (if (symbolp address)
348 (defun elpher-address-special-p (address)
349 "Return non-nil if ADDRESS object is special (e.g. start page, bookmarks page)."
352 (defun elpher-address-gopher-p (address)
353 "Return non-nill if ADDRESS object is a gopher address."
354 (and (not (elpher-address-special-p address))
355 (member (elpher-address-protocol address) '("gopher gophers"))))
357 (defun elpher-gopher-address-selector (address)
358 "Retrieve gopher selector from ADDRESS object."
359 (if (member (url-filename address) '("" "/"))
361 (url-unhex-string (substring (url-filename address) 2))))
366 (defvar elpher-content-cache (make-hash-table :test 'equal))
367 (defvar elpher-pos-cache (make-hash-table :test 'equal))
369 (defun elpher-get-cached-content (address)
370 "Retrieve the cached content for ADDRESS, or nil if none exists."
371 (gethash address elpher-content-cache))
373 (defun elpher-cache-content (address content)
374 "Set the content cache for ADDRESS to CONTENT."
375 (puthash address content elpher-content-cache))
377 (defun elpher-get-cached-pos (address)
378 "Retrieve the cached cursor position for ADDRESS, or nil if none exists."
379 (gethash address elpher-pos-cache))
381 (defun elpher-cache-pos (address pos)
382 "Set the cursor position cache for ADDRESS to POS."
383 (puthash address pos elpher-pos-cache))
388 (defun elpher-make-page (display-string address)
389 "Create a page with DISPLAY-STRING and ADDRESS."
390 (list display-string address))
392 (defun elpher-page-display-string (page)
393 "Retrieve the display string corresponding to PAGE."
396 (defun elpher-page-address (page)
397 "Retrieve the address corresponding to PAGE."
400 (defun elpher-page-set-address (page new-address)
401 "Set the address corresponding to PAGE to NEW-ADDRESS."
402 (setcar (cdr page) new-address))
404 (defvar elpher-current-page nil)
405 (defvar elpher-history nil)
407 (defun elpher-visit-page (page &optional renderer no-history)
408 "Visit PAGE using its own renderer or RENDERER, if non-nil.
409 Additionally, push PAGE onto the stack of previously-visited pages,
410 unless NO-HISTORY is non-nil."
412 (elpher-process-cleanup)
413 (unless (or no-history
414 (equal (elpher-page-address elpher-current-page)
415 (elpher-page-address page)))
416 (push elpher-current-page elpher-history))
417 (setq elpher-current-page page)
418 (let* ((address (elpher-page-address page))
419 (type (elpher-address-type address))
420 (type-record (cdr (assoc type elpher-type-map))))
422 (funcall (car type-record)
426 (elpher-visit-previous-page)
428 (`(gopher ,type-char)
429 (error "Unsupported gopher selector type '%c' for '%s'"
430 type-char (elpher-address-to-url address)))
432 (error "Unsupported address type '%S' for '%s'"
433 other (elpher-address-to-url address)))))))
435 (defun elpher-visit-previous-page ()
436 "Visit the previous page in the history."
437 (let ((previous-page (pop elpher-history)))
439 (elpher-visit-page previous-page nil t)
440 (error "No previous page"))))
442 (defun elpher-reload-current-page ()
443 "Reload the current page, discarding any existing cached content."
444 (elpher-cache-content (elpher-page-address elpher-current-page) nil)
445 (elpher-visit-page elpher-current-page))
447 (defun elpher-save-pos ()
448 "Save the current position of point to the current page."
449 (when elpher-current-page
450 (elpher-cache-pos (elpher-page-address elpher-current-page) (point))))
452 (defun elpher-restore-pos ()
453 "Restore the position of point to that cached in the current page."
454 (let ((pos (elpher-get-cached-pos (elpher-page-address elpher-current-page))))
457 (goto-char (point-min)))))
460 ;;; Buffer preparation
463 (defun elpher-update-header ()
464 "If `elpher-use-header' is true, display current page info in window header."
465 (if elpher-use-header
466 (let* ((display-string (elpher-page-display-string elpher-current-page))
467 (address (elpher-page-address elpher-current-page))
468 (tls-string (if (and (not (elpher-address-special-p address))
469 (member (elpher-address-protocol address)
470 '("gophers" "gemini")))
473 (header (concat display-string
474 (propertize tls-string 'face 'bold))))
475 (setq header-line-format header))))
477 (defmacro elpher-with-clean-buffer (&rest args)
478 "Evaluate ARGS with a clean *elpher* buffer as current."
479 (list 'with-current-buffer "*elpher*"
481 (append (list 'let '((inhibit-read-only t))
482 '(setq-local network-security-level
483 (default-value 'network-security-level))
485 '(elpher-update-header))
492 (defvar elpher-user-coding-system nil
493 "User-specified coding system to use for decoding text responses.")
495 (defun elpher-decode (string)
496 "Decode STRING using autodetected or user-specified coding system."
497 (decode-coding-string string
498 (if elpher-user-coding-system
499 elpher-user-coding-system
500 (detect-coding-string string t))))
502 (defun elpher-preprocess-text-response (string)
503 "Preprocess text selector response contained in STRING.
504 This involes decoding the character representation, and clearing
505 away CRs and any terminating period."
506 (elpher-decode (replace-regexp-in-string "\n\.\n$" "\n"
507 (replace-regexp-in-string "\r" "" string))))
510 ;;; Network error reporting
513 (defun elpher-network-error (address error)
514 "Display ERROR message following unsuccessful negotiation with ADDRESS.
515 ERROR can be either an error object or a string."
516 (elpher-with-clean-buffer
517 (insert (propertize "\n---- ERROR -----\n\n" 'face 'error)
518 "When attempting to retrieve " (elpher-address-to-url address) ":\n"
519 (if (stringp error) error (error-message-string error)) "\n"
520 (propertize "\n----------------\n\n" 'face 'error)
521 "Press 'u' to return to the previous page.")))
524 ;;; Gopher selector retrieval
527 (defvar elpher-network-timer nil
528 "Timer used for network connections.")
530 (defun elpher-process-cleanup ()
531 "Immediately shut down any extant elpher process and timers."
532 (let ((p (get-process "elpher-process")))
533 (if p (delete-process p)))
534 (if (timerp elpher-network-timer)
535 (cancel-timer elpher-network-timer)))
537 (defvar elpher-use-tls nil
538 "If non-nil, use TLS to communicate with gopher servers.")
540 (defun elpher-get-selector (address renderer &optional force-ipv4)
541 "Retrieve selector specified by ADDRESS, then render it using RENDERER.
542 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
544 (when (equal (elpher-address-protocol address) "gophers")
545 (if (gnutls-available-p)
546 (when (not elpher-use-tls)
547 (setq elpher-use-tls t)
548 (message "Engaging TLS gopher mode."))
549 (error "Cannot retrieve TLS gopher selector: GnuTLS not available")))
550 (unless (< (elpher-address-port address) 65536)
551 (error "Cannot retrieve gopher selector: port number > 65536"))
553 (let* ((kill-buffer-query-functions nil)
554 (gnutls-verify-error nil) ; We use the NSM for verification
555 (port (elpher-address-port address))
556 (host (elpher-address-host address))
557 (selector-string-parts nil)
560 (proc (open-network-stream "elpher-process"
562 (if force-ipv4 (dns-query host) host)
563 (if (> port 0) port 70)
564 :type (if elpher-use-tls 'tls 'plain)
566 (timer (run-at-time elpher-connection-timeout
569 (pcase (process-status proc)
571 (if (and (not (equal (elpher-address-protocol address)
574 (or elpher-auto-disengage-TLS
575 (yes-or-no-p "Could not establish encrypted connection. Disable TLS mode?")))
577 (message "Disabling TLS mode.")
578 (setq elpher-use-tls nil)
579 (elpher-get-selector address renderer))
580 (elpher-network-error address "Could not establish encrypted connection")))
582 (elpher-process-cleanup)
584 (message "Connection timed out. Retrying with IPv4 address.")
585 (elpher-get-selector address renderer t))))))))
586 (setq elpher-network-timer timer)
587 (set-process-coding-system proc 'binary)
588 (set-process-filter proc
589 (lambda (_proc string)
593 (setq bytes-received (+ bytes-received (length string)))
594 (let ((new-hkbytes-received (/ bytes-received 102400)))
595 (when (> new-hkbytes-received hkbytes-received)
596 (setq hkbytes-received new-hkbytes-received)
597 (with-current-buffer "*elpher*"
598 (let ((inhibit-read-only t))
599 (goto-char (point-min))
600 (beginning-of-line 2)
601 (delete-region (point) (point-max))
603 (number-to-string (/ hkbytes-received 10.0))
605 (setq selector-string-parts
606 (cons string selector-string-parts))))
607 (set-process-sentinel proc
608 (lambda (_proc event)
609 (condition-case the-error
611 ((string-prefix-p "deleted" event))
612 ((string-prefix-p "open" event)
613 (let ((inhibit-eol-conversion t))
616 (concat (elpher-gopher-address-selector address)
622 (funcall renderer (apply #'concat
623 (reverse selector-string-parts)))
624 (elpher-restore-pos)))
626 (elpher-network-error address the-error))))))
628 (error "Error initiating connection to server"))))
630 (defun elpher-get-gopher-page (renderer)
631 "Getter function for gopher pages.
632 The RENDERER procedure is used to display the contents of the page
633 once they are retrieved from the gopher server."
634 (let* ((address (elpher-page-address elpher-current-page))
635 (content (elpher-get-cached-content address)))
636 (if (and content (funcall renderer nil))
637 (elpher-with-clean-buffer
639 (elpher-restore-pos))
640 (elpher-with-clean-buffer
641 (insert "LOADING... (use 'u' to cancel)\n"))
642 (condition-case the-error
643 (elpher-get-selector address renderer)
645 (elpher-network-error address the-error))))))
649 (defun elpher-insert-index (string)
650 "Insert the index corresponding to STRING into the current buffer."
651 ;; Should be able to split directly on CRLF, but some non-conformant
652 ;; LF-only servers sadly exist, hence the following.
653 (let ((str-processed (elpher-preprocess-text-response string)))
654 (dolist (line (split-string str-processed "\n"))
656 (unless (= (length line) 0)
657 (let* ((type (elt line 0))
658 (fields (split-string (substring line 1) "\t"))
659 (display-string (elt fields 0))
660 (selector (elt fields 1))
661 (host (elt fields 2))
662 (port (if (elt fields 3)
663 (string-to-number (elt fields 3))
665 (address (elpher-make-gopher-address type selector host port)))
666 (elpher-insert-index-record display-string address)))))))
668 (defun elpher-insert-margin (&optional type-name)
669 "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
672 (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
674 (propertize "[" 'face 'elpher-margin-brackets)
675 (propertize type-name 'face 'elpher-margin-key)
676 (propertize "]" 'face 'elpher-margin-brackets))))
678 (insert (make-string elpher-margin-width ?\s))))
680 (defun elpher-page-button-help (page)
681 "Return a string containing the help text for a button corresponding to PAGE."
682 (let ((address (elpher-page-address page)))
683 (format "mouse-1, RET: open '%s'" (if (elpher-address-special-p address)
685 (elpher-address-to-url address)))))
687 (defun elpher-insert-index-record (display-string &optional address)
688 "Function to insert an index record into the current buffer.
689 The contents of the record are dictated by DISPLAY-STRING and ADDRESS.
690 If ADDRESS is not supplied or nil the record is rendered as an
692 (let* ((type (if address (elpher-address-type address) nil))
693 (type-map-entry (cdr (assoc type elpher-type-map))))
695 (let* ((margin-code (elt type-map-entry 2))
696 (face (elt type-map-entry 3))
697 (filtered-display-string (ansi-color-filter-apply display-string))
698 (page (elpher-make-page filtered-display-string address)))
699 (elpher-insert-margin margin-code)
700 (insert-text-button filtered-display-string
703 'action #'elpher-click-link
705 'help-echo (elpher-page-button-help page)))
708 (elpher-insert-margin)
709 (let ((propertized-display-string
710 (propertize display-string 'face 'elpher-info)))
711 (insert (elpher-process-text-for-display propertized-display-string))))
712 (`(gopher ,selector-type) ;; Unknown
713 (elpher-insert-margin (concat (char-to-string selector-type) "?"))
714 (insert (propertize display-string
715 'face 'elpher-unknown)))))
718 (defun elpher-click-link (button)
719 "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
720 (let ((page (button-get button 'elpher-page)))
721 (elpher-visit-page page)))
723 (defun elpher-render-index (data &optional _mime-type-string)
724 "Render DATA as an index. MIME-TYPE-STRING is unused."
725 (elpher-with-clean-buffer
728 (elpher-insert-index data)
729 (elpher-cache-content (elpher-page-address elpher-current-page)
734 (defconst elpher-url-regex
735 "\\([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\-_~?/@|#]\\)?\\)?"
736 "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
738 (defun elpher-buttonify-urls (string)
739 "Turn substrings which look like urls in STRING into clickable buttons."
742 (goto-char (point-min))
743 (while (re-search-forward elpher-url-regex nil t)
744 (let ((page (elpher-make-page (substring-no-properties (match-string 0))
745 (elpher-address-from-url (match-string 0)))))
746 (make-text-button (match-beginning 0)
749 'action #'elpher-click-link
751 'help-echo (elpher-page-button-help page)
755 (defconst elpher-ansi-regex "\x1b\\[[^m]*m"
756 "Wildly incomplete regexp used to strip out some troublesome ANSI escape sequences.")
758 (defun elpher-process-text-for-display (string)
759 "Perform any desired processing of STRING prior to display as text.
760 Currently includes buttonifying URLs and processing ANSI escape codes."
761 (elpher-buttonify-urls (if elpher-filter-ansi-from-text
762 (ansi-color-filter-apply string)
763 (ansi-color-apply string))))
765 (defun elpher-render-text (data &optional _mime-type-string)
766 "Render DATA as text. MIME-TYPE-STRING is unused."
767 (elpher-with-clean-buffer
770 (insert (elpher-process-text-for-display (elpher-preprocess-text-response data)))
771 (elpher-cache-content
772 (elpher-page-address elpher-current-page)
777 (defun elpher-render-image (data &optional _mime-type-string)
778 "Display DATA as image. MIME-TYPE-STRING is unused."
781 (if (display-images-p)
783 (let ((image (create-image
786 (elpher-with-clean-buffer
788 (elpher-restore-pos))))
789 (elpher-render-download data))))
791 ;; Search retrieval and rendering
793 (defun elpher-get-gopher-query-page (renderer)
794 "Getter for gopher addresses requiring input.
795 The response is rendered using the rendering function RENDERER."
796 (let* ((address (elpher-page-address elpher-current-page))
797 (content (elpher-get-cached-content address))
799 (if (and content (funcall renderer nil))
800 (elpher-with-clean-buffer
803 (message "Displaying cached search results. Reload to perform a new search."))
805 (let* ((query-string (read-string "Query: "))
806 (query-selector (concat (elpher-gopher-address-selector address) "\t" query-string))
807 (search-address (elpher-make-gopher-address ?1
809 (elpher-address-host address)
810 (elpher-address-port address)
811 (equal (elpher-address-type address) "gophers"))))
814 (elpher-with-clean-buffer
815 (insert "LOADING RESULTS... (use 'u' to cancel)"))
816 (elpher-get-selector search-address renderer))
818 (elpher-visit-previous-page))))))
820 ;; Raw server response rendering
822 (defun elpher-render-raw (data &optional mime-type-string)
823 "Display raw DATA in buffer. MIME-TYPE-STRING is also displayed if provided."
826 (elpher-with-clean-buffer
827 (when mime-type-string
828 (insert "MIME type specified by server: '" mime-type-string "'\n"))
830 (goto-char (point-min)))
831 (message "Displaying raw server response. Reload or redraw to return to standard view.")))
833 ;; File save "rendering"
835 (defun elpher-render-download (data &optional _mime-type-string)
836 "Save DATA to file. MIME-TYPE-STRING is unused."
839 (let* ((address (elpher-page-address elpher-current-page))
840 (selector (if (elpher-address-gopher-p address)
841 (elpher-gopher-address-selector address)
842 (elpher-address-filename address))))
843 (elpher-visit-previous-page) ; Do first in case of non-local exits.
844 (let* ((filename-proposal (file-name-nondirectory selector))
845 (filename (read-file-name "Download complete. Save file as: "
847 (if (> (length filename-proposal) 0)
850 (let ((coding-system-for-write 'binary))
851 (with-temp-file filename
853 (message (format "Saved to file %s." filename))))))
857 (defun elpher-render-html (data &optional _mime-type-string)
858 "Render DATA as HTML using shr. MIME-TYPE-STRING is unused."
859 (elpher-with-clean-buffer
862 (let ((dom (with-temp-buffer
864 (libxml-parse-html-region (point-min) (point-max)))))
865 (shr-insert-document dom)))))
867 ;; Gemini page retrieval
869 (defvar elpher-gemini-redirect-chain)
871 (defun elpher-get-gemini-response (address renderer &optional force-ipv4)
872 "Retrieve gemini ADDRESS, then render using RENDERER.
873 If FORCE-IPV4 is non-nil, explicitly look up and use IPv4 address corresponding
875 (unless elpher-gemini-TLS-cert-checks
876 (setq-local network-security-level 'low))
877 (if (not (gnutls-available-p))
878 (error "Cannot establish gemini connection: GnuTLS not available")
879 (unless (< (elpher-address-port address) 65536)
880 (error "Cannot establish gemini connection: port number > 65536"))
882 (let* ((kill-buffer-query-functions nil)
883 (gnutls-verify-error nil) ; We use the NSM for verification
884 (port (elpher-address-port address))
885 (host (elpher-address-host address))
886 (response-string-parts nil)
889 (proc (open-network-stream "elpher-process"
891 (if force-ipv4 (dns-query host) host)
892 (if (> port 0) port 1965)
895 (timer (run-at-time elpher-connection-timeout nil
897 (elpher-process-cleanup)
899 ; Try again with IPv4
900 (message "Connection timed out. Retrying with IPv4.")
901 (elpher-get-gemini-response address renderer t))))))
902 (setq elpher-network-timer timer)
903 (set-process-coding-system proc 'binary)
904 (set-process-filter proc
905 (lambda (_proc string)
909 (setq bytes-received (+ bytes-received (length string)))
910 (let ((new-hkbytes-received (/ bytes-received 102400)))
911 (when (> new-hkbytes-received hkbytes-received)
912 (setq hkbytes-received new-hkbytes-received)
913 (with-current-buffer "*elpher*"
914 (let ((inhibit-read-only t))
915 (goto-char (point-min))
916 (beginning-of-line 2)
917 (delete-region (point) (point-max))
919 (number-to-string (/ hkbytes-received 10.0))
921 (setq response-string-parts
922 (cons string response-string-parts))))
923 (set-process-sentinel proc
925 (condition-case the-error
927 ((string-prefix-p "open" event) ; request URL
928 (let ((inhibit-eol-conversion t))
931 (concat (elpher-address-to-url address)
933 ((string-prefix-p "deleted" event)) ; do nothing
934 ((and (not response-string-parts)
936 ; Try again with IPv4
937 (message "Connection failed. Retrying with IPv4.")
939 (elpher-get-gemini-response address renderer t))
941 (funcall #'elpher-process-gemini-response
942 (apply #'concat (reverse response-string-parts))
944 (elpher-restore-pos)))
946 (elpher-network-error address the-error))))))
948 (error "Error initiating connection to server")))))
950 (defun elpher-parse-gemini-response (response)
951 "Parse the RESPONSE string and return a list of components.
952 The list is of the form (code meta body). A response of nil implies
953 that the response was malformed."
954 (let ((header-end-idx (string-match "\r\n" response)))
956 (let ((header (string-trim (substring response 0 header-end-idx)))
957 (body (substring response (+ header-end-idx 2))))
958 (if (>= (length header) 2)
959 (let ((code (substring header 0 2))
960 (meta (string-trim (substring header 2))))
961 (list code meta body))
962 (error "Malformed response: No response status found in header %s" header)))
963 (error "Malformed response: No CRLF-delimited header found in response %s" response))))
965 (defun elpher-process-gemini-response (response-string renderer)
966 "Process the gemini response RESPONSE-STRING and pass the result to RENDERER."
967 (let ((response-components (elpher-parse-gemini-response response-string)))
968 (let ((response-code (elt response-components 0))
969 (response-meta (elt response-components 1))
970 (response-body (elt response-components 2)))
971 (pcase (elt response-code 0)
973 (elpher-with-clean-buffer
974 (insert "Gemini server is requesting input."))
975 (let* ((query-string (read-string (concat response-meta ": ")))
976 (url (elpher-address-to-url (elpher-page-address elpher-current-page)))
977 (query-address (elpher-address-from-url (concat url "?" query-string))))
978 (elpher-get-gemini-response query-address renderer)))
979 (?2 ; Normal response
980 (funcall renderer response-body response-meta))
982 (message "Following redirect to %s" response-meta)
983 (if (>= (length elpher-gemini-redirect-chain) 5)
984 (error "More than 5 consecutive redirects followed"))
985 (let ((redirect-address (elpher-address-from-gemini-url response-meta)))
986 (if (member redirect-address elpher-gemini-redirect-chain)
987 (error "Redirect loop detected"))
988 (if (not (string= (elpher-address-protocol redirect-address)
990 (error "Server tried to automatically redirect to non-gemini URL: %s"
992 (elpher-page-set-address elpher-current-page redirect-address)
993 (add-to-list 'elpher-gemini-redirect-chain redirect-address)
994 (elpher-get-gemini-response redirect-address renderer)))
995 (?4 ; Temporary failure
996 (error "Gemini server reports TEMPORARY FAILURE for this request: %s %s"
997 response-code response-meta))
998 (?5 ; Permanent failure
999 (error "Gemini server reports PERMANENT FAILURE for this request: %s %s"
1000 response-code response-meta))
1001 (?6 ; Client certificate required
1002 (error "Gemini server requires client certificate (unsupported at this time)"))
1004 (error "Gemini server response unknown: %s %s"
1005 response-code response-meta))))))
1007 (defun elpher-get-gemini-page (renderer)
1008 "Getter which retrieves and renders a Gemini page and renders it using RENDERER."
1009 (let* ((address (elpher-page-address elpher-current-page))
1010 (content (elpher-get-cached-content address)))
1011 (condition-case the-error
1012 (if (and content (funcall renderer nil))
1013 (elpher-with-clean-buffer
1015 (elpher-restore-pos))
1016 (elpher-with-clean-buffer
1017 (insert "LOADING GEMINI... (use 'u' to cancel)\n"))
1018 (setq elpher-gemini-redirect-chain nil)
1019 (elpher-get-gemini-response address renderer))
1021 (elpher-network-error address the-error)))))
1024 (defun elpher-render-gemini (body &optional mime-type-string)
1025 "Render gemini response BODY with rendering MIME-TYPE-STRING."
1028 (let* ((mime-type-string* (if (or (not mime-type-string)
1029 (string-empty-p mime-type-string))
1030 "text/gemini; charset=utf-8"
1032 (mime-type-split (split-string mime-type-string* ";" t))
1033 (mime-type (string-trim (car mime-type-split)))
1034 (parameters (mapcar (lambda (s)
1035 (let ((key-val (split-string s "=")))
1036 (list (downcase (string-trim (car key-val)))
1037 (downcase (string-trim (cadr key-val))))))
1038 (cdr mime-type-split))))
1039 (when (string-prefix-p "text/" mime-type)
1040 (setq body (decode-coding-string
1042 (if (assoc "charset" parameters)
1043 (intern (cadr (assoc "charset" parameters)))
1045 (setq body (replace-regexp-in-string "\r" "" body)))
1047 ((or "text/gemini" "")
1048 (elpher-render-gemini-map body parameters))
1050 (elpher-render-html body))
1051 ((pred (string-prefix-p "text/"))
1052 (elpher-render-gemini-plain-text body parameters))
1053 ((pred (string-prefix-p "image/"))
1054 (elpher-render-image body))
1056 (elpher-render-download body))))))
1058 (defun elpher-gemini-get-link-url (link-line)
1059 "Extract the url portion of LINK-LINE, a gemini map file link line.
1060 Returns nil in the event that the contents of the line following the
1061 => prefix are empty."
1062 (let ((l (split-string (substring link-line 2))))
1064 (string-trim (elt l 0))
1067 (defun elpher-gemini-get-link-display-string (link-line)
1068 "Extract the display string portion of LINK-LINE, a gemini map file link line.
1069 Returns the url portion in the event that the display-string portion is empty."
1070 (let* ((rest (string-trim (elt (split-string link-line "=>") 1)))
1071 (idx (string-match "[ \t]" rest)))
1072 (string-trim (if idx
1073 (substring rest (+ idx 1))
1076 (defun elpher-collapse-dot-sequences (filename)
1077 "Collapse dot sequences in FILENAME.
1078 For instance, the filename /a/b/../c/./d will reduce to /a/c/d"
1079 (let* ((path (split-string filename "/"))
1080 (path-reversed-normalized
1081 (seq-reduce (lambda (a b)
1082 (cond ((and a (equal b "..") (cdr a)))
1083 ((and (not a) (equal b "..")) a) ;leading .. are dropped
1087 (string-join (reverse path-reversed-normalized) "/")))
1089 (defun elpher-address-from-gemini-url (url)
1090 "Extract address from URL with defaults as per gemini map files."
1091 (let ((address (url-generic-parse-url url)))
1092 (unless (and (url-type address) (not (url-fullness address))) ;avoid mangling mailto: urls
1093 (setf (url-fullness address) t)
1094 (if (url-host address) ;if there is an explicit host, filenames are absolute
1095 (if (string-empty-p (url-filename address))
1096 (setf (url-filename address) "/")) ;ensure empty filename is marked as absolute
1097 (setf (url-host address) (url-host (elpher-page-address elpher-current-page)))
1098 (unless (string-prefix-p "/" (url-filename address)) ;deal with relative links
1099 (setf (url-filename address)
1100 (concat (file-name-directory
1101 (url-filename (elpher-page-address elpher-current-page)))
1102 (url-filename address)))))
1103 (unless (url-type address)
1104 (setf (url-type address) "gemini"))
1105 (if (equal (url-type address) "gemini")
1106 (setf (url-filename address)
1107 (elpher-collapse-dot-sequences (url-filename address)))))
1110 (defun elpher-gemini-insert-link (link-line)
1111 "Insert link described by LINK-LINE into a text/gemini document."
1112 (let* ((url (elpher-gemini-get-link-url link-line))
1113 (display-string (elpher-gemini-get-link-display-string link-line))
1114 (address (elpher-address-from-gemini-url url))
1115 (type (if address (elpher-address-type address) nil))
1116 (type-map-entry (cdr (assoc type elpher-type-map))))
1117 (when display-string
1120 (let* ((face (elt type-map-entry 3))
1121 (filtered-display-string (ansi-color-filter-apply display-string))
1122 (page (elpher-make-page filtered-display-string address)))
1123 (insert-text-button filtered-display-string
1126 'action #'elpher-click-link
1128 'help-echo (elpher-page-button-help page)))
1129 (insert (propertize display-string 'face 'elpher-unknown)))
1132 (defun elpher-gemini-insert-header (header-line)
1133 "Insert header described by HEADER-LINE into a text/gemini document.
1134 The gemini map file line describing the header is given
1136 (when (string-match "^\\(#+\\)[ \t]*" header-line)
1137 (let ((level (length (match-string 1 header-line)))
1138 (header (substring header-line (match-end 0))))
1139 (unless (display-graphic-p)
1140 (insert (make-string level ?#) " "))
1141 (insert (propertize header 'face
1143 (1 'elpher-gemini-heading1)
1144 (2 'elpher-gemini-heading2)
1145 (3 'elpher-gemini-heading3)
1149 (defun elpher-gemini-insert-text (text-line)
1150 "Insert a plain non-preformatted TEXT-LINE into a text/gemini document.
1151 This function uses Emacs' auto-fill to wrap text sensibly to a maximum
1152 width defined by elpher-gemini-max-fill-width."
1153 (insert (elpher-process-text-for-display text-line))
1154 (let* ((prefix-end-idx (string-match "^[ \t]*\\(\*+[ \t]\\)?" text-line))
1155 (fill-prefix (replace-regexp-in-string "\*" " " (match-string 0 text-line))))
1158 (defun elpher-render-gemini-map (data _parameters)
1159 "Render DATA as a gemini map file, PARAMETERS is currently unused."
1160 (elpher-with-clean-buffer
1161 (let ((preformatted nil))
1163 (setq-local fill-column (min (window-width) elpher-gemini-max-fill-width))
1164 (dolist (line (split-string data "\n"))
1166 ((string-prefix-p "```" line) (setq preformatted (not preformatted)))
1167 (preformatted (insert (elpher-process-text-for-display
1168 (propertize line 'face 'elpher-gemini-preformatted))
1170 ((string-prefix-p "=>" line) (elpher-gemini-insert-link line))
1171 ((string-prefix-p "#" line) (elpher-gemini-insert-header line))
1172 (t (elpher-gemini-insert-text line)))))
1173 (elpher-cache-content
1174 (elpher-page-address elpher-current-page)
1177 (defun elpher-render-gemini-plain-text (data _parameters)
1178 "Render DATA as plain text file. PARAMETERS is currently unused."
1179 (elpher-with-clean-buffer
1180 (insert (elpher-process-text-for-display data))
1181 (elpher-cache-content
1182 (elpher-page-address elpher-current-page)
1185 ;; Finger page connection
1187 (defun elpher-get-finger-page (renderer &optional force-ipv4)
1188 "Opens a finger connection to the current page address and renders it using RENDERER."
1189 (let* ((address (elpher-page-address elpher-current-page))
1190 (content (elpher-get-cached-content address)))
1191 (if (and content (funcall renderer nil))
1192 (elpher-with-clean-buffer
1194 (elpher-restore-pos))
1195 (elpher-with-clean-buffer
1196 (insert "LOADING... (use 'u' to cancel)\n"))
1197 (condition-case the-error
1198 (let* ((kill-buffer-query-functions nil)
1199 (user (let ((filename (elpher-address-filename address)))
1200 (if (> (length filename) 1)
1201 (substring filename 1)
1202 (elpher-address-user address))))
1203 (port (let ((given-port (elpher-address-port address)))
1204 (if (> given-port 0) given-port 79)))
1205 (host (elpher-address-host address))
1206 (selector-string-parts nil)
1207 (proc (open-network-stream "elpher-process"
1209 (if force-ipv4 (dns-query host) host)
1213 (timer (run-at-time elpher-connection-timeout
1216 (pcase (process-status proc)
1218 (elpher-process-cleanup)
1220 (message "Connection timed out. Retrying with IPv4 address.")
1221 (elpher-get-finger-page renderer t))))))))
1222 (setq elpher-network-timer timer)
1223 (set-process-coding-system proc 'binary)
1224 (set-process-filter proc
1225 (lambda (_proc string)
1227 (cancel-timer timer)
1229 (setq selector-string-parts
1230 (cons string selector-string-parts))))
1231 (set-process-sentinel proc
1232 (lambda (_proc event)
1233 (condition-case the-error
1235 ((string-prefix-p "deleted" event))
1236 ((string-prefix-p "open" event)
1237 (let ((inhibit-eol-conversion t))
1238 (process-send-string
1240 (concat user "\r\n"))))
1243 (cancel-timer timer)
1245 (funcall renderer (apply #'concat
1246 (reverse selector-string-parts)))
1247 (elpher-restore-pos)))))))
1249 (elpher-network-error address the-error))))))
1252 ;; Other URL page opening
1254 (defun elpher-get-other-url-page (renderer)
1255 "Getter which attempts to open the URL specified by the current page (RENDERER must be nil)."
1257 (elpher-visit-previous-page)
1258 (error "Command not supported for general URLs"))
1259 (let* ((address (elpher-page-address elpher-current-page))
1260 (url (elpher-address-to-url address)))
1262 (elpher-visit-previous-page) ; Do first in case of non-local exits.
1263 (message "Opening URL...")
1264 (if elpher-open-urls-with-eww
1266 (browse-url url)))))
1268 ;; Telnet page connection
1270 (defun elpher-get-telnet-page (renderer)
1271 "Opens a telnet connection to the current page address (RENDERER must be nil)."
1273 (elpher-visit-previous-page)
1274 (error "Command not supported for telnet URLs"))
1275 (let* ((address (elpher-page-address elpher-current-page))
1276 (host (elpher-address-host address))
1277 (port (elpher-address-port address)))
1278 (elpher-visit-previous-page)
1283 ;; Start page page retrieval
1285 (defun elpher-get-start-page (renderer)
1286 "Getter which displays the start page (RENDERER must be nil)."
1288 (elpher-visit-previous-page)
1289 (error "Command not supported for start page"))
1290 (elpher-with-clean-buffer
1291 (insert " --------------------------------------------\n"
1292 " Elpher Gopher and Gemini Client \n"
1293 " version " elpher-version "\n"
1294 " --------------------------------------------\n"
1296 "Default bindings:\n"
1298 " - TAB/Shift-TAB: next/prev item on current page\n"
1299 " - RET/mouse-1: open item under cursor\n"
1300 " - m: select an item on current page by name (autocompletes)\n"
1301 " - u/mouse-3: return to previous page\n"
1302 " - o/O: visit different selector or the root menu of the current server\n"
1303 " - g: go to a particular address (gopher, gemini, finger)\n"
1304 " - d/D: download item under cursor or current page\n"
1305 " - i/I: info on item under cursor or current page\n"
1306 " - c/C: copy URL representation of item under cursor or current page\n"
1307 " - a/A: bookmark the item under cursor or current page\n"
1308 " - x/X: remove bookmark for item under cursor or current page\n"
1309 " - B: visit the bookmarks page\n"
1310 " - r: redraw current page (using cached contents if available)\n"
1311 " - R: reload current page (regenerates cache)\n"
1312 " - S: set character coding system for gopher (default is to autodetect)\n"
1313 " - T: toggle TLS gopher mode\n"
1314 " - .: display the raw server response for the current page\n"
1316 "Start your exploration of gopher space and gemini:\n")
1317 (elpher-insert-index-record "Floodgap Systems Gopher Server"
1318 (elpher-make-gopher-address ?1 "" "gopher.floodgap.com" 70))
1319 (elpher-insert-index-record "Project Gemini home page"
1320 (elpher-address-from-url "gemini://gemini.circumlunar.space/"))
1322 "Alternatively, select a search engine and enter some search terms:\n")
1323 (elpher-insert-index-record "Gopher Search Engine (Veronica-2)"
1324 (elpher-make-gopher-address ?7 "/v2/vs" "gopher.floodgap.com" 70))
1325 (elpher-insert-index-record "Gemini Search Engine (GUS)"
1326 (elpher-address-from-url "gemini://gus.guru/search"))
1328 "This page contains your bookmarked sites (also visit with B):\n")
1329 (elpher-insert-index-record "Your Bookmarks" 'bookmarks)
1331 "For Elpher release news or to leave feedback, visit:\n")
1332 (elpher-insert-index-record "The Elpher Project Page"
1333 (elpher-make-gopher-address ?1
1339 (let ((help-string "RET,mouse-1: Open Elpher info manual (if available)"))
1340 (insert-text-button "Elpher info manual"
1346 'help-echo help-string))
1347 (insert " for the full documentation. **\n")
1349 (concat " (This should be available if you have installed Elpher using\n"
1350 " MELPA. Otherwise you will have to install the manual yourself.)\n")
1352 (elpher-restore-pos)))
1354 ;; Bookmarks page page retrieval
1356 (defun elpher-get-bookmarks-page (renderer)
1357 "Getter to load and display the current bookmark list (RENDERER must be nil)."
1359 (elpher-visit-previous-page)
1360 (error "Command not supported for bookmarks page"))
1361 (elpher-with-clean-buffer
1362 (insert "---- Bookmark list ----\n\n")
1363 (let ((bookmarks (elpher-load-bookmarks)))
1365 (dolist (bookmark bookmarks)
1366 (let ((display-string (elpher-bookmark-display-string bookmark))
1367 (address (elpher-address-from-url (elpher-bookmark-url bookmark))))
1368 (elpher-insert-index-record display-string address)))
1369 (insert "No bookmarks found.\n")))
1370 (insert "\n-----------------------\n"
1372 "- u: return to previous page\n"
1373 "- x: delete selected bookmark\n"
1374 "- a: rename selected bookmark\n"
1376 "Bookmarks are stored in the file ")
1377 (let ((filename elpher-bookmarks-file)
1378 (help-string "RET,mouse-1: Open bookmarks file in new buffer for editing."))
1379 (insert-text-button filename
1383 (find-file filename))
1385 'help-echo help-string))
1387 (elpher-restore-pos)))
1393 (defun elpher-make-bookmark (display-string url)
1394 "Make an elpher bookmark.
1395 DISPLAY-STRING determines how the bookmark will appear in the
1396 bookmark list, while URL is the url of the entry."
1397 (list display-string url))
1399 (defun elpher-bookmark-display-string (bookmark)
1400 "Get the display string of BOOKMARK."
1403 (defun elpher-set-bookmark-display-string (bookmark display-string)
1404 "Set the display string of BOOKMARK to DISPLAY-STRING."
1405 (setcar bookmark display-string))
1407 (defun elpher-bookmark-url (bookmark)
1408 "Get the address for BOOKMARK."
1411 (defun elpher-save-bookmarks (bookmarks)
1412 "Record the bookmark list BOOKMARKS to the user's bookmark file.
1413 Beware that this completely replaces the existing contents of the file."
1414 (with-temp-file elpher-bookmarks-file
1416 (insert "; Elpher bookmarks file\n\n"
1417 "; Bookmarks are stored as a list of (label URL) items.\n"
1418 "; Feel free to edit by hand, but take care to ensure\n"
1419 "; the list structure remains intact.\n\n")
1420 (pp bookmarks (current-buffer))))
1422 (defun elpher-load-bookmarks ()
1423 "Get the list of bookmarks from the users's bookmark file."
1427 (insert-file-contents elpher-bookmarks-file)
1428 (goto-char (point-min))
1429 (read (current-buffer))))))
1430 (if (and bookmarks (listp (cadar bookmarks)))
1432 (message "Reading old bookmark file. (Will be updated on write.)")
1433 (mapcar (lambda (old-bm)
1435 (elpher-address-to-url (apply #'elpher-make-gopher-address
1440 (defun elpher-add-address-bookmark (address display-string)
1441 "Save a bookmark for ADDRESS with label DISPLAY-STRING.)))
1442 If ADDRESS is already bookmarked, update the label only."
1443 (let ((bookmarks (elpher-load-bookmarks))
1444 (url (elpher-address-to-url address)))
1445 (let ((existing-bookmark (rassoc (list url) bookmarks)))
1446 (if existing-bookmark
1447 (elpher-set-bookmark-display-string existing-bookmark display-string)
1448 (push (elpher-make-bookmark display-string url) bookmarks)))
1449 (elpher-save-bookmarks bookmarks)))
1451 (defun elpher-remove-address-bookmark (address)
1452 "Remove any bookmark to ADDRESS."
1453 (let ((url (elpher-address-to-url address)))
1454 (elpher-save-bookmarks
1455 (seq-filter (lambda (bookmark)
1456 (not (equal (elpher-bookmark-url bookmark) url)))
1457 (elpher-load-bookmarks)))))
1459 ;;; Interactive procedures
1462 (defun elpher-next-link ()
1463 "Move point to the next link on the current page."
1467 (defun elpher-prev-link ()
1468 "Move point to the previous link on the current page."
1470 (backward-button 1))
1472 (defun elpher-follow-current-link ()
1473 "Open the link or url at point."
1477 (defun elpher-go (host-or-url)
1478 "Go to a particular gopher site HOST-OR-URL.
1479 When run interactively HOST-OR-URL is read from the minibuffer."
1480 (interactive "sGopher or Gemini URL: ")
1481 (let ((page (elpher-make-page host-or-url
1482 (elpher-address-from-url host-or-url))))
1483 (switch-to-buffer "*elpher*")
1484 (elpher-visit-page page)
1487 (defun elpher-go-current ()
1488 "Go to a particular site read from the minibuffer, initialized with the current URL."
1490 (let ((address (elpher-page-address elpher-current-page)))
1491 (if (elpher-address-special-p address)
1492 (error "Command invalid for this page")
1493 (let ((url (read-string "Gopher or Gemini URL: " (elpher-address-to-url address))))
1494 (elpher-visit-page (elpher-make-page url (elpher-address-from-url url)))))))
1496 (defun elpher-redraw ()
1497 "Redraw current page."
1499 (elpher-visit-page elpher-current-page))
1501 (defun elpher-reload ()
1502 "Reload current page."
1504 (elpher-reload-current-page))
1506 (defun elpher-toggle-tls ()
1507 "Toggle TLS encryption mode for gopher."
1509 (setq elpher-use-tls (not elpher-use-tls))
1511 (if (gnutls-available-p)
1512 (message "TLS gopher mode enabled. (Will not affect current page until reload.)")
1513 (setq elpher-use-tls nil)
1514 (error "Cannot enable TLS gopher mode: GnuTLS not available"))
1515 (message "TLS gopher mode disabled. (Will not affect current page until reload.)")))
1517 (defun elpher-view-raw ()
1518 "View raw server response for current page."
1520 (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1521 (error "This page was not generated by a server")
1522 (elpher-visit-page elpher-current-page
1523 #'elpher-render-raw)))
1525 (defun elpher-back ()
1526 "Go to previous site."
1528 (elpher-visit-previous-page))
1530 (defun elpher-download ()
1531 "Download the link at point."
1533 (let ((button (button-at (point))))
1535 (let ((page (button-get button 'elpher-page)))
1536 (if (elpher-address-special-p (elpher-page-address page))
1537 (error "Cannot download %s"
1538 (elpher-page-display-string page))
1539 (elpher-visit-page (button-get button 'elpher-page)
1540 #'elpher-render-download)))
1541 (error "No link selected"))))
1543 (defun elpher-download-current ()
1544 "Download the current page."
1546 (if (elpher-address-special-p (elpher-page-address elpher-current-page))
1547 (error "Cannot download %s"
1548 (elpher-page-display-string elpher-current-page))
1549 (elpher-visit-page (elpher-make-page
1550 (elpher-page-display-string elpher-current-page)
1551 (elpher-page-address elpher-current-page))
1552 #'elpher-render-download
1555 (defun elpher-build-link-map ()
1556 "Build alist mapping link names to destination pages in current buffer."
1557 (let ((link-map nil)
1558 (b (next-button (point-min) t)))
1560 (push (cons (button-label b) b) link-map)
1561 (setq b (next-button (button-start b))))
1564 (defun elpher-jump ()
1565 "Select a directory entry by name. Similar to the info browser (m)enu command."
1567 (let* ((link-map (elpher-build-link-map)))
1569 (let ((key (let ((completion-ignore-case t))
1570 (completing-read "Directory item/link: "
1572 (if (and key (> (length key) 0))
1573 (let ((b (cdr (assoc key link-map))))
1574 (goto-char (button-start b))
1575 (button-activate b)))))))
1577 (defun elpher-root-dir ()
1578 "Visit root of current server."
1580 (let ((address (elpher-page-address elpher-current-page)))
1581 (if (not (elpher-address-special-p address))
1582 (if (or (member (url-filename address) '("/" ""))
1583 (and (elpher-address-gopher-p address)
1584 (= (length (elpher-gopher-address-selector address)) 0)))
1585 (error "Already at root directory of current server")
1586 (let ((address-copy (elpher-address-from-url
1587 (elpher-address-to-url address))))
1588 (setf (url-filename address-copy) "")
1589 (elpher-go (elpher-address-to-url address-copy))))
1590 (error "Command invalid for %s" (elpher-page-display-string elpher-current-page)))))
1592 (defun elpher-bookmarks-current-p ()
1593 "Return non-nil if current page is a bookmarks page."
1594 (equal (elpher-address-type (elpher-page-address elpher-current-page))
1595 '(special bookmarks)))
1597 (defun elpher-reload-bookmarks ()
1598 "Reload bookmarks if current page is a bookmarks page."
1599 (if (elpher-bookmarks-current-p)
1600 (elpher-reload-current-page)))
1602 (defun elpher-bookmark-current ()
1603 "Bookmark the current page."
1605 (let ((address (elpher-page-address elpher-current-page))
1606 (display-string (elpher-page-display-string elpher-current-page)))
1607 (if (not (elpher-address-special-p address))
1608 (let ((bookmark-display-string (read-string "Bookmark display string: "
1610 (elpher-add-address-bookmark address bookmark-display-string)
1611 (message "Bookmark added."))
1612 (error "Cannot bookmark %s" display-string))))
1614 (defun elpher-bookmark-link ()
1615 "Bookmark the link at point."
1617 (let ((button (button-at (point))))
1619 (let* ((page (button-get button 'elpher-page))
1620 (address (elpher-page-address page))
1621 (display-string (elpher-page-display-string page)))
1622 (if (not (elpher-address-special-p address))
1623 (let ((bookmark-display-string (read-string "Bookmark display string: "
1625 (elpher-add-address-bookmark address bookmark-display-string)
1626 (elpher-reload-bookmarks)
1627 (message "Bookmark added."))
1628 (error "Cannot bookmark %s" display-string)))
1629 (error "No link selected"))))
1631 (defun elpher-unbookmark-current ()
1632 "Remove bookmark for the current page."
1634 (let ((address (elpher-page-address elpher-current-page)))
1635 (unless (elpher-address-special-p address)
1636 (elpher-remove-address-bookmark address)
1637 (message "Bookmark removed."))))
1639 (defun elpher-unbookmark-link ()
1640 "Remove bookmark for the link at point."
1642 (let ((button (button-at (point))))
1644 (let ((page (button-get button 'elpher-page)))
1645 (elpher-remove-address-bookmark (elpher-page-address page))
1646 (elpher-reload-bookmarks)
1647 (message "Bookmark removed."))
1648 (error "No link selected"))))
1650 (defun elpher-bookmarks ()
1651 "Visit bookmarks page."
1653 (switch-to-buffer "*elpher*")
1655 (elpher-make-page "Bookmarks Page" (elpher-make-special-address 'bookmarks))))
1657 (defun elpher-info-page (page)
1658 "Display information on PAGE."
1659 (let ((display-string (elpher-page-display-string page))
1660 (address (elpher-page-address page)))
1661 (if (elpher-address-special-p address)
1662 (message "Special page: %s" display-string)
1663 (message "%s" (elpher-address-to-url address)))))
1665 (defun elpher-info-link ()
1666 "Display information on page corresponding to link at point."
1668 (let ((button (button-at (point))))
1670 (elpher-info-page (button-get button 'elpher-page))
1671 (error "No item selected"))))
1673 (defun elpher-info-current ()
1674 "Display information on current page."
1676 (elpher-info-page elpher-current-page))
1678 (defun elpher-copy-page-url (page)
1679 "Copy URL representation of address of PAGE to `kill-ring'."
1680 (let ((address (elpher-page-address page)))
1681 (if (elpher-address-special-p address)
1682 (error (format "Cannot represent %s as URL" (elpher-page-display-string page)))
1683 (let ((url (elpher-address-to-url address)))
1684 (message "Copied \"%s\" to kill-ring/clipboard." url)
1687 (defun elpher-copy-link-url ()
1688 "Copy URL of item at point to `kill-ring'."
1690 (let ((button (button-at (point))))
1692 (elpher-copy-page-url (button-get button 'elpher-page))
1693 (error "No item selected"))))
1695 (defun elpher-copy-current-url ()
1696 "Copy URL of current page to `kill-ring'."
1698 (elpher-copy-page-url elpher-current-page))
1700 (defun elpher-set-gopher-coding-system ()
1701 "Specify an explicit character coding system for gopher selectors."
1703 (let ((system (read-coding-system "Set coding system to use for gopher (default is to autodetect): " nil)))
1704 (setq elpher-user-coding-system system)
1706 (message "Gopher coding system fixed to %s. (Reload to see effect)." system)
1707 (message "Gopher coding system set to autodetect. (Reload to see effect)."))))
1713 (defvar elpher-mode-map
1714 (let ((map (make-sparse-keymap)))
1715 (define-key map (kbd "TAB") 'elpher-next-link)
1716 (define-key map (kbd "<backtab>") 'elpher-prev-link)
1717 (define-key map (kbd "C-M-i") 'elpher-prev-link)
1718 (define-key map (kbd "u") 'elpher-back)
1719 (define-key map [mouse-3] 'elpher-back)
1720 (define-key map (kbd "O") 'elpher-root-dir)
1721 (define-key map (kbd "g") 'elpher-go)
1722 (define-key map (kbd "o") 'elpher-go-current)
1723 (define-key map (kbd "r") 'elpher-redraw)
1724 (define-key map (kbd "R") 'elpher-reload)
1725 (define-key map (kbd "T") 'elpher-toggle-tls)
1726 (define-key map (kbd ".") 'elpher-view-raw)
1727 (define-key map (kbd "d") 'elpher-download)
1728 (define-key map (kbd "D") 'elpher-download-current)
1729 (define-key map (kbd "m") 'elpher-jump)
1730 (define-key map (kbd "i") 'elpher-info-link)
1731 (define-key map (kbd "I") 'elpher-info-current)
1732 (define-key map (kbd "c") 'elpher-copy-link-url)
1733 (define-key map (kbd "C") 'elpher-copy-current-url)
1734 (define-key map (kbd "a") 'elpher-bookmark-link)
1735 (define-key map (kbd "A") 'elpher-bookmark-current)
1736 (define-key map (kbd "x") 'elpher-unbookmark-link)
1737 (define-key map (kbd "X") 'elpher-unbookmark-current)
1738 (define-key map (kbd "B") 'elpher-bookmarks)
1739 (define-key map (kbd "S") 'elpher-set-gopher-coding-system)
1740 (when (fboundp 'evil-define-key*)
1741 (evil-define-key* 'motion map
1742 (kbd "TAB") 'elpher-next-link
1743 (kbd "C-") 'elpher-follow-current-link
1744 (kbd "C-t") 'elpher-back
1745 (kbd "u") 'elpher-back
1746 [mouse-3] 'elpher-back
1747 (kbd "g") 'elpher-go
1748 (kbd "o") 'elpher-go-current
1749 (kbd "r") 'elpher-redraw
1750 (kbd "R") 'elpher-reload
1751 (kbd "T") 'elpher-toggle-tls
1752 (kbd ".") 'elpher-view-raw
1753 (kbd "d") 'elpher-download
1754 (kbd "D") 'elpher-download-current
1755 (kbd "m") 'elpher-jump
1756 (kbd "i") 'elpher-info-link
1757 (kbd "I") 'elpher-info-current
1758 (kbd "c") 'elpher-copy-link-url
1759 (kbd "C") 'elpher-copy-current-url
1760 (kbd "a") 'elpher-bookmark-link
1761 (kbd "A") 'elpher-bookmark-current
1762 (kbd "x") 'elpher-unbookmark-link
1763 (kbd "X") 'elpher-unbookmark-current
1764 (kbd "B") 'elpher-bookmarks
1765 (kbd "S") 'elpher-set-gopher-coding-system))
1767 "Keymap for gopher client.")
1769 (define-derived-mode elpher-mode special-mode "elpher"
1770 "Major mode for elpher, an elisp gopher client.
1772 This mode is automatically enabled by the interactive
1773 functions which initialize the gopher client, namely
1774 `elpher', `elpher-go' and `elpher-bookmarks'.")
1776 (when (fboundp 'evil-set-initial-state)
1777 (evil-set-initial-state 'elpher-mode 'motion))
1780 ;;; Main start procedure
1785 "Start elpher with default landing page."
1787 (if (get-buffer "*elpher*")
1788 (switch-to-buffer "*elpher*")
1789 (switch-to-buffer "*elpher*")
1790 (setq elpher-current-page nil)
1791 (setq elpher-history nil)
1792 (let ((start-page (elpher-make-page "Elpher Start Page"
1793 (elpher-make-special-address 'start))))
1794 (elpher-visit-page start-page)))
1795 "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
1797 ;;; elpher.el ends here