Renamed package.
[elpher.git] / elpher.el
1 ;;; elpher.el --- elisp gopher client
2
3 ;;; Commentary:
4
5 ;; An elisp gopher client.
6
7 ;;; Code:
8
9 ;;; Global constants
10 ;;
11
12 (defconst elpher-version "1.0.0"
13   "Current version of elpher.")
14
15 (defconst elpher-margin-width 6
16   "Width of left-hand margin used when rendering indicies.")
17
18 (defconst elpher-start-index
19   (mapconcat
20    'identity
21    (list "i\tfake\tfake\t1"
22          "i--------------------------------------------\tfake\tfake\t1"
23          "i          Elpher Gopher Client             \tfake\tfake\t1"
24          (format "i              version %s\tfake\tfake\t1" elpher-version)
25          "i--------------------------------------------\tfake\tfake\t1"
26          "i\tfake\tfake\t1"
27          "iBasic usage:\tfake\tfake\t1"
28          "i\tfake\tfake\t1"
29          "i - tab/shift-tab: next/prev directory entry on current page\tfake\tfake\t1"
30          "i - RET/mouse-1: open directory entry under cursor\tfake\tfake\t1"
31          "i - u: return to parent directory entry\tfake\tfake\t1"
32          "i - g: go to a particular page\tfake\tfake\t1"
33          "i - r: redraw current page (using cached contents if available)\tfake\tfake\t1"
34          "i - R: reload current page (regenerates cache)\tfake\tfake\t1"
35          "i - d: download directory entry under cursor\tfake\tfake\t1"
36          "i - w: display the raw server response for the current page\tfake\tfake\t1"
37          "i\tfake\tfake\t1"
38          "iPlaces to start exploring Gopherspace:\tfake\tfake\t1"
39          "i\tfake\tfake\t1"
40          "1Floodgap Systems Gopher Server\t\tgopher.floodgap.com\t70"
41          "i\tfake\tfake\t1"
42          "iAlternatively, select the following item and enter some\tfake\tfake\t1"
43          "isearch terms:\tfake\tfake\t1"
44          "i\tfake\tfake\t1"
45          "7Veronica-2 Gopher Search Engine\t/v2/vs\tgopher.floodgap.com\t70"
46          ".")
47    "\r\n")
48   "Source for elpher start page.")
49
50
51 ;;; Customization group
52 ;;
53
54 (defgroup elpher nil
55   "A gopher client."
56   :group 'applications)
57
58 (defface elpher-index
59   '((((background dark)) :foreground "deep sky blue")
60     (((background light)) :foreground "blue"))
61   "Face used for index records.")
62
63 (defface elpher-text
64   '((((background dark)) :foreground "white")
65     (((background light)) :weight bold))
66   "Face used for text records.")
67
68 (defface elpher-info '()
69   "Face used for info records.")
70
71 (defface elpher-image
72   '((((background dark)) :foreground "green")
73     (t :foreground "dark green"))
74   "Face used for image records.")
75
76 (defface elpher-search
77   '((((background light)) :foreground "orange")
78     (((background dark)) :foreground "dark orange"))
79   "Face used for search records.")
80
81 (defface elpher-url
82   '((((background dark)) :foreground "yellow")
83     (((background light)) :foreground "dark red"))
84   "Face used for url records.")
85
86 (defface elpher-binary
87   '((t :foreground "magenta"))
88   "Face used for binary records.")
89
90 (defface elpher-unknown
91   '((t :foreground "red"))
92   "Face used for unknown record types.")
93
94 (defface elpher-margin-key
95   '((((background dark)) :foreground "white"))
96   "Face used for margin key.")
97
98 (defface elpher-margin-brackets
99   '((t :foreground "blue"))
100   "Face used for brackets around margin key.")
101
102 (defcustom elpher-open-urls-with-eww nil
103   "If non-nil, open URL selectors using eww.
104 Otherwise, use the system browser via the BROWSE-URL function."
105   :type '(boolean))
106
107 ;;; Model
108 ;;
109
110 ;; Address
111
112 (defun elpher-make-address (selector host port)
113   "Create an address of a gopher object with SELECTOR, HOST and PORT."
114   (list selector host port))
115
116 (defun elpher-address-selector (address)
117   "Retrieve selector from ADDRESS."
118   (car address))
119
120 (defun elpher-address-host (address)
121   "Retrieve host from ADDRESS."
122   (cadr address))
123
124 (defun elpher-address-port (address)
125   "Retrieve port from ADDRESS."
126   (caddr address))
127
128 ;; Node
129
130 (defun elpher-make-node (parent address getter &optional content pos)
131   "Create a node in the gopher page hierarchy.
132
133 PARENT specifies the parent of the node, ADDRESS specifies the address of
134 the gopher page, GETTER provides the getter function used to obtain this
135 page.
136
137 The optional arguments CONTENT and POS can be used to fill the cached
138 content and cursor position fields of the node."
139   (list parent address getter content pos))
140
141 (defun elpher-node-parent (node)
142   "Retrieve the parent node of NODE."
143   (elt node 0))
144
145 (defun elpher-node-address (node)
146   "Retrieve the address of NODE."
147   (elt node 1))
148
149 (defun elpher-node-getter (node)
150   "Retrieve the preferred getter function of NODE."
151   (elt node 2))
152
153 (defun elpher-node-content (node)
154   "Retrieve the cached content of NODE, or nil if none exists."
155   (elt node 3))
156
157 (defun elpher-node-pos (node)
158   "Retrieve the cached cursor position for NODE, or nil if none exists."
159   (elt node 4))
160
161 (defun elpher-set-node-content (node content)
162   "Set the content cache of NODE to CONTENT."
163   (setcar (nthcdr 3 node) content))
164
165 (defun elpher-set-node-pos (node pos)
166   "Set the cursor position cache of NODE to POS."
167   (setcar (nthcdr 4 node) pos))
168
169 ;; Node graph traversal
170
171 (defvar elpher-current-node)
172
173 (defun elpher-visit-node (node &optional getter)
174   "Visit NODE using its own getter or GETTER, if non-nil."
175   (elpher-save-pos)
176   (elpher-process-cleanup)
177   (setq elpher-current-node node)
178   (if getter
179       (funcall getter)
180     (funcall (elpher-node-getter node))))
181
182 (defun elpher-visit-parent-node ()
183   "Visit the parent of the current node."
184   (let ((parent-node (elpher-node-parent elpher-current-node)))
185     (when parent-node
186       (elpher-visit-node parent-node))))
187       
188 (defun elpher-reload-current-node ()
189   "Reload the current node, discarding any existing cached content."
190   (elpher-set-node-content elpher-current-node nil)
191   (elpher-visit-node elpher-current-node))
192
193 (defun elpher-save-pos ()
194   "Save the current position of point to the current node."
195   (when elpher-current-node
196     (elpher-set-node-pos elpher-current-node (point))))
197
198 (defun elpher-restore-pos ()
199   "Restore the position of point to that cached in the current node."
200   (let ((pos (elpher-node-pos elpher-current-node)))
201     (if pos
202         (goto-char pos)
203       (goto-char (point-min)))))
204
205 ;;; Buffer preparation
206 ;;
207
208 (defmacro elpher-with-clean-buffer (&rest args)
209   "Evaluate ARGS with a clean *elpher* buffer as current."
210   (list 'progn
211         '(switch-to-buffer "*elpher*")
212         '(elpher-mode)
213         (append (list 'let '((inhibit-read-only t))
214                       '(erase-buffer))
215                 args)))
216
217 ;;; Index rendering
218 ;;
219
220 (defun elpher-insert-index (string)
221   "Insert the index corresponding to STRING into the current buffer."
222   (dolist (line (split-string string "\r\n"))
223     (unless (= (length line) 0)
224       (elpher-insert-index-record line))))
225
226 (defun elpher-insert-margin (&optional type-name)
227   "Insert index margin, optionally containing the TYPE-NAME, into the current buffer."
228   (if type-name
229       (progn
230         (insert (format (concat "%" (number-to-string (- elpher-margin-width 1)) "s")
231                         (concat
232                          (propertize "[" 'face 'elpher-margin-brackets)
233                          (propertize type-name 'face 'elpher-margin-key)
234                          (propertize "]" 'face 'elpher-margin-brackets))))
235         (insert " "))
236     (insert (make-string elpher-margin-width ?\s))))
237
238 (defvar elpher-type-map
239   '((?0 elpher-get-text-node "T" elpher-text)
240     (?1 elpher-get-index-node "/" elpher-index)
241     (?g elpher-get-image-node "im" elpher-image)
242     (?p elpher-get-image-node "im" elpher-image)
243     (?I elpher-get-image-node "im" elpher-image)
244     (?4 elpher-get-node-download "B" elpher-binary)
245     (?5 elpher-get-node-download "B" elpher-binary)
246     (?9 elpher-get-node-download "B" elpher-binary)
247     (?7 elpher-get-search-node "?" elpher-search))
248   "Association list from types to getters, margin codes and index faces.")
249
250 (defun elpher-insert-index-record (line)
251   "Insert the index record corresponding to LINE into the current buffer."
252   (let* ((type (elt line 0))
253          (fields (split-string (substring line 1) "\t"))
254          (display-string (elt fields 0))
255          (selector (elt fields 1))
256          (host (elt fields 2))
257          (port (elt fields 3))
258          (address (elpher-make-address selector host port))
259          (type-map-entry (alist-get type elpher-type-map)))
260     (if type-map-entry
261         (let ((getter (car type-map-entry))
262               (margin-code (cadr type-map-entry))
263               (face (caddr type-map-entry)))
264           (elpher-insert-margin margin-code)
265           (insert-text-button display-string
266                               'face face
267                               'elpher-node (elpher-make-node elpher-current-node
268                                                                address
269                                                                getter)
270                               'action #'elpher-click-link
271                               'follow-link t
272                               'help-echo (format "mouse-1, RET: open %s on %s port %s"
273                                                  selector host port)))
274       (pcase type
275         (?i (elpher-insert-margin) ; Information
276             (insert (propertize display-string
277                                 'face 'elpher-info)))
278         (?h (elpher-insert-margin "W") ; Web link
279             (let ((url (elt (split-string selector "URL:") 1)))
280               (insert-text-button display-string
281                                   'face 'elpher-url
282                                   'elpher-url url
283                                   'action #'elpher-click-url
284                                   'follow-link t
285                                   'help-echo (format "mouse-1, RET: open url %s" url))))
286         (?.) ; Occurs at end of index, can safely ignore.
287         (tp (elpher-insert-margin (concat (char-to-string tp) "?"))
288             (insert (propertize display-string
289                                 'face 'elpher-unknown-face)))))
290     (insert "\n")))
291
292
293 ;;; Selector retrieval (all kinds)
294 ;;
295
296 (defun elpher-process-cleanup ()
297   "Immediately shut down any extant elpher process."
298   (let ((p (get-process "elpher-process")))
299     (if p (delete-process p))))
300
301 (defvar elpher-selector-string)
302
303 (defun elpher-get-selector (address after)
304   "Retrieve selector specified by ADDRESS, then execute AFTER.
305 The result is stored as a string in the variable elpher-selector-string."
306   (setq elpher-selector-string "")
307   (make-network-process
308    :name "elpher-process"
309    :host (elpher-address-host address)
310    :service (elpher-address-port address)
311    :filter (lambda (proc string)
312              (setq elpher-selector-string (concat elpher-selector-string string)))
313    :sentinel after)
314   (process-send-string "elpher-process"
315                        (concat (elpher-address-selector address) "\n")))
316
317 ;; Index retrieval
318
319 (defun elpher-get-index-node ()
320   "Getter which retrieves the current node contents as an index."
321   (let ((content (elpher-node-content elpher-current-node))
322         (address (elpher-node-address elpher-current-node)))
323     (if content
324         (progn
325           (elpher-with-clean-buffer
326            (insert content))
327           (elpher-restore-pos))
328       (if address
329           (progn
330             (elpher-with-clean-buffer
331              (insert "LOADING DIRECTORY..."))
332             (elpher-get-selector address
333                                   (lambda (proc event)
334                                     (unless (string-prefix-p "deleted" event)
335                                       (elpher-with-clean-buffer
336                                        (elpher-insert-index elpher-selector-string))
337                                       (elpher-restore-pos)
338                                       (elpher-set-node-content elpher-current-node
339                                                                 (buffer-string))))))
340         (progn
341           (elpher-with-clean-buffer
342            (elpher-insert-index elpher-start-index))
343           (elpher-restore-pos)
344           (elpher-set-node-content elpher-current-node
345                                     (buffer-string)))))))
346
347 ;; Text retrieval
348
349 (defconst elpher-url-regex
350   "\\(https?\\|gopher\\)://\\([a-zA-Z0-9.\-]+\\)\\(?3::[0-9]+\\)?\\(?4:/[^ \r\n\t(),]*\\)?"
351   "Regexp used to locate and buttinofy URLs in text files loaded by elpher.")
352
353 (defun elpher-buttonify-urls (string)
354   "Turn substrings which look like urls in STRING into clickable buttons."
355   (with-temp-buffer
356     (insert string)
357     (goto-char (point-min))
358     (while (re-search-forward elpher-url-regex nil t)
359       (let ((url (match-string 0))
360             (protocol (downcase (match-string 1))))
361         (if (string= protocol "gopher")
362             (let* ((host (match-string 2))
363                    (port 70)
364                    (type-and-selector (match-string 4))
365                    (type (if (> (length type-and-selector) 1)
366                              (elt type-and-selector 1)
367                            ?1))
368                    (selector (if (> (length type-and-selector) 1)
369                                  (substring type-and-selector 2)
370                                ""))
371                    (address (elpher-make-address selector host port))
372                    (getter (car (alist-get type elpher-type-map))))
373               (make-text-button (match-beginning 0)
374                                 (match-end 0)
375                                 'elpher-node (elpher-make-node elpher-current-node
376                                                                  address
377                                                                  getter)
378                                 'action #'elpher-click-link
379                                 'follow-link t
380                                 'help-echo (format "mouse-1, RET: open %s on %s port %s"
381                                                    selector host port)))
382           (make-text-button (match-beginning 0)
383                             (match-end 0)
384                             'elpher-url url
385                             'action #'elpher-click-url
386                             'follow-link t
387                             'help-echo (format "mouse-1, RET: open url %s" url)))))
388     (buffer-string)))
389
390 (defun elpher-process-text (string)
391   "Remove CRs and trailing period from the gopher text document STRING."
392   (let* ((chopped-str (replace-regexp-in-string "\r\n\.\r\n$" "\r\n" string))
393          (cleaned-str (replace-regexp-in-string "\r" "" chopped-str)))
394     (elpher-buttonify-urls cleaned-str)))
395
396 (defun elpher-get-text-node ()
397   "Getter which retrieves the current node contents as a text document."
398   (let ((content (elpher-node-content elpher-current-node))
399         (address (elpher-node-address elpher-current-node)))
400     (if content
401         (progn
402           (elpher-with-clean-buffer
403            (insert content))
404           (elpher-restore-pos))
405       (progn
406         (elpher-with-clean-buffer
407          (insert "LOADING TEXT..."))
408         (elpher-get-selector address
409                               (lambda (proc event)
410                                 (unless (string-prefix-p "deleted" event)
411                                   (elpher-with-clean-buffer
412                                    (insert (elpher-process-text elpher-selector-string)))
413                                   (elpher-restore-pos)
414                                   (elpher-set-node-content elpher-current-node
415                                                             (buffer-string)))))))))
416
417 ;; Image retrieval
418
419 (defun elpher-get-image-node ()
420   "Getter which retrieves the current node contents as an image to view."
421   (let ((content (elpher-node-content elpher-current-node))
422         (address (elpher-node-address elpher-current-node)))
423     (if content
424         (progn
425           (elpher-with-clean-buffer
426            (insert-image content))
427           (setq cursor-type nil)
428           (elpher-restore-pos))
429       (progn
430         (elpher-with-clean-buffer
431          (insert "LOADING IMAGE..."))
432         (elpher-get-selector address
433                               (lambda (proc event)
434                                 (unless (string-prefix-p "deleted" event)
435                                   (let ((image (create-image
436                                                 (encode-coding-string elpher-selector-string
437                                                                       'no-conversion)
438                                                 nil t)))
439                                     (elpher-with-clean-buffer
440                                      (insert-image image))
441                                     (setq cursor-type nil)
442                                     (elpher-restore-pos)
443                                     (elpher-set-node-content elpher-current-node
444                                                               image)))))))))
445
446 ;; Search retrieval
447
448 (defun elpher-get-search-node ()
449   "Getter which submits a search query to the address of the current node."
450   (let ((content (elpher-node-content elpher-current-node))
451         (address (elpher-node-address elpher-current-node))
452         (aborted t))
453     (if content
454         (progn
455           (elpher-with-clean-buffer
456            (insert content))
457           (elpher-restore-pos)
458           (message "Displaying cached search results.  Reload to perform a new search."))
459       (unwind-protect
460           (let* ((query-string (read-string "Query: "))
461                  (query-selector (concat (elpher-address-selector address) "\t" query-string))
462                  (search-address (elpher-make-address query-selector
463                                                        (elpher-address-host address)
464                                                        (elpher-address-port address))))
465             (setq aborted nil)
466             (elpher-with-clean-buffer
467              (insert "LOADING RESULTS..."))
468             (elpher-get-selector search-address
469                                   (lambda (proc event)
470                                     (unless (string-prefix-p "deleted" event)
471                                       (elpher-with-clean-buffer
472                                        (elpher-insert-index elpher-selector-string))
473                                       (goto-char (point-min))
474                                       (elpher-set-node-content elpher-current-node
475                                                                 (buffer-string))))))
476         (if aborted
477             (elpher-visit-parent-node))))))
478
479 ;; Raw server response retrieval
480
481 (defun elpher-get-node-raw ()
482   "Getter which retrieves the raw server response for the current node."
483   (let* ((content (elpher-node-content elpher-current-node))
484          (address (elpher-node-address elpher-current-node)))
485     (elpher-with-clean-buffer
486      (insert "LOADING RAW SERVER RESPONSE..."))
487     (if address
488         (elpher-get-selector address
489                               (lambda (proc event)
490                                 (unless (string-prefix-p "deleted" event)
491                                   (elpher-with-clean-buffer
492                                    (insert elpher-selector-string))
493                                   (goto-char (point-min)))))
494       (progn
495         (elpher-with-clean-buffer
496          (insert elpher-start-index))
497         (goto-char (point-min)))))
498   (message "Displaying raw server response.  Reload or redraw to return to standard view."))
499  
500 ;; File export retrieval
501
502 (defvar elpher-download-filename)
503
504 (defun elpher-get-node-download ()
505   "Getter which retrieves the current node and writes the result to a file."
506   (let* ((address (elpher-node-address elpher-current-node))
507          (selector (elpher-address-selector address)))
508     (elpher-visit-parent-node) ; Do first in case of non-local exits.
509     (let* ((filename-proposal (file-name-nondirectory selector))
510            (filename (read-file-name "Save file as: "
511                                      nil nil nil
512                                      (if (> (length filename-proposal) 0)
513                                          filename-proposal
514                                        "gopher.file"))))
515       (message "Downloading...")
516       (setq elpher-download-filename filename)
517       (elpher-get-selector address
518                             (lambda (proc event)
519                               (let ((coding-system-for-write 'binary))
520                                 (with-temp-file elpher-download-filename
521                                   (insert elpher-selector-string)
522                                   (message (format "Download complate, saved to file %s."
523                                                    elpher-download-filename)))))))))
524
525
526 ;;; Navigation procedures
527 ;;
528
529 (defun elpher-next-link ()
530   "Move point to the next link on the current page."
531   (interactive)
532   (forward-button 1))
533
534 (defun elpher-prev-link ()
535   "Move point to the previous link on the current page."
536   (interactive)
537   (backward-button 1))
538
539 (defun elpher-click-link (button)
540   "Function called when the gopher link BUTTON is activated (via mouse or keypress)."
541   (let ((node (button-get button 'elpher-node)))
542     (elpher-visit-node node)))
543
544 (defun elpher-click-url (button)
545   "Function called when the url link BUTTON is activated (via mouse or keypress)."
546   (let ((url (button-get button 'elpher-url)))
547     (if elpher-open-urls-with-eww
548         (browse-web url)
549       (browse-url url))))
550
551 (defun elpher-follow-current-link ()
552   "Open the link or url at point."
553   (interactive)
554   (push-button))
555
556 (defun elpher-go ()
557   "Go to a particular gopher site."
558   (interactive)
559   (let* (
560          (hostname (read-string "Gopher host: "))
561          (selector (read-string "Selector (default none): " nil nil ""))
562          (port (read-string "Port (default 70): " nil nil 70))
563          (address (list selector hostname port)))
564     (elpher-visit-node
565      (elpher-make-node elpher-current-node
566                         address
567                         #'elpher-get-index-node))))
568
569 (defun  elpher-redraw ()
570   "Redraw current page."
571   (interactive)
572   (elpher-visit-node elpher-current-node))
573
574 (defun  elpher-reload ()
575   "Reload current page."
576   (interactive)
577   (elpher-reload-current-node))
578
579 (defun elpher-view-raw ()
580   "View current page as plain text."
581   (interactive)
582   (elpher-visit-node elpher-current-node
583                       #'elpher-get-node-raw))
584
585 (defun elpher-back ()
586   "Go to previous site."
587   (interactive)
588   (if (elpher-node-parent elpher-current-node)
589       (elpher-visit-parent-node)
590     (message "No previous site.")))
591
592 (defun elpher-download ()
593   "Download the link at point."
594   (interactive)
595   (let ((button (button-at (point))))
596     (if button
597         (let ((node (button-get button 'elpher-node)))
598           (if node
599               (elpher-visit-node (button-get button 'elpher-node)
600                                   #'elpher-get-node-download)
601             (message "Can only download gopher links, not general URLs.")))
602       (message "No link selected."))))
603
604 ;;; Mode and keymap
605 ;;
606
607 (defvar elpher-mode-map
608   (let ((map (make-sparse-keymap)))
609     (define-key map (kbd "TAB") 'elpher-next-link)
610     (define-key map (kbd "<backtab>") 'elpher-prev-link)
611     (define-key map (kbd "u") 'elpher-back)
612     (define-key map (kbd "g") 'elpher-go)
613     (define-key map (kbd "r") 'elpher-redraw)
614     (define-key map (kbd "R") 'elpher-reload)
615     (define-key map (kbd "w") 'elpher-view-raw)
616     (define-key map (kbd "d") 'elpher-download)
617     (when (fboundp 'evil-define-key)
618       (evil-define-key 'normal map
619         (kbd "TAB") 'elpher-next-link
620         (kbd "C-]") 'elpher-follow-current-link
621         (kbd "C-t") 'elpher-back
622         (kbd "u") 'elpher-back
623         (kbd "g") 'elpher-go
624         (kbd "r") 'elpher-redraw
625         (kbd "R") 'elpher-reload
626         (kbd "w") 'elpher-view-raw
627         (kbd "d") 'elpher-download))
628     map)
629   "Keymap for gopher client.")
630
631 (define-derived-mode elpher-mode special-mode "elpher"
632   "Major mode for elpher, an elisp gopher client.")
633
634
635 ;;; Main start procedure
636 ;;
637
638 ;;;###autoload
639 (defun elpher ()
640   "Start elpher with default landing page."
641   (interactive)
642   (setq elpher-current-node nil)
643   (let ((start-node (elpher-make-node nil nil #'elpher-get-index-node)))
644     (elpher-visit-node start-node))
645   "Started Elpher.") ; Otherwise (elpher) evaluates to start page string.
646
647 ;;; elpher.el ends here