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