Start implementing the various url and image interactive commands.
[gnus] / lisp / shr.el
1 ;;; shr.el --- Simple HTML Renderer
2
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: html
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This package takes a HTML parse tree (as provided by
26 ;; libxml-parse-html-region) and renders it in the current buffer.  It
27 ;; does not do CSS, JavaScript or anything advanced: It's geared
28 ;; towards rendering typical short snippets of HTML, like what you'd
29 ;; find in HTML email and the like.
30
31 ;;; Code:
32
33 (require 'browse-url)
34
35 (defgroup shr nil
36   "Simple HTML Renderer"
37   :group 'mail)
38
39 (defcustom shr-max-image-proportion 0.9
40   "How big pictures displayed are in relation to the window they're in.
41 A value of 0.7 means that they are allowed to take up 70% of the
42 width and height of the window.  If they are larger than this,
43 and Emacs supports it, then the images will be rescaled down to
44 fit these criteria."
45   :version "24.1"
46   :group 'shr
47   :type 'float)
48
49 (defcustom shr-blocked-images nil
50   "Images that have URLs matching this regexp will be blocked."
51   :version "24.1"
52   :group 'shr
53   :type 'regexp)
54
55 (defvar shr-folding-mode nil)
56 (defvar shr-state nil)
57 (defvar shr-start nil)
58 (defvar shr-indentation 0)
59
60 (defvar shr-width 70)
61
62 (defvar shr-map
63   (let ((map (make-sparse-keymap)))
64     (define-key map "a" 'shr-show-alt-text)
65     (define-key map "i" 'shr-browse-image)
66     (define-key map "I" 'shr-insert-image)
67     (define-key map "u" 'shr-copy-string)
68     (define-key map "v" 'shr-browse-url)
69     map))
70
71 (defun shr-transform-dom (dom)
72   (let ((result (list (pop dom))))
73     (dolist (arg (pop dom))
74       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
75                   (cdr arg))
76             result))
77     (dolist (sub dom)
78       (if (stringp sub)
79           (push (cons :text sub) result)
80         (push (shr-transform-dom sub) result)))
81     (nreverse result)))
82
83 ;;;###autoload
84 (defun shr-insert-document (dom)
85   (let ((shr-state nil)
86         (shr-start nil))
87     (shr-descend (shr-transform-dom dom))))
88
89 (defun shr-descend (dom)
90   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
91     (if (fboundp function)
92         (funcall function (cdr dom))
93       (shr-generic (cdr dom)))))
94
95 (defun shr-generic (cont)
96   (dolist (sub cont)
97     (cond
98      ((eq (car sub) :text)
99       (shr-insert (cdr sub)))
100      ((listp (cdr sub))
101       (shr-descend sub)))))
102
103 (defun shr-tag-p (cont)
104   (shr-ensure-paragraph)
105   (shr-generic cont)
106   (shr-ensure-paragraph))
107
108 (defun shr-ensure-paragraph ()
109   (unless (bobp)
110     (if (bolp)
111         (unless (save-excursion
112                   (forward-line -1)
113                   (looking-at " *$"))
114           (insert "\n"))
115       (if (save-excursion
116             (beginning-of-line)
117             (looking-at " *$"))
118           (insert "\n")
119         (insert "\n\n")))))
120
121 (defun shr-tag-b (cont)
122   (shr-fontize-cont cont 'bold))
123
124 (defun shr-tag-i (cont)
125   (shr-fontize-cont cont 'italic))
126
127 (defun shr-tag-u (cont)
128   (shr-fontize-cont cont 'underline))
129
130 (defun shr-tag-s (cont)
131   (shr-fontize-cont cont 'strike-through))
132
133 (defun shr-fontize-cont (cont &rest types)
134   (let (shr-start)
135     (shr-generic cont)
136     (dolist (type types)
137       (shr-add-font (or shr-start (point)) (point) type))))
138
139 (defun shr-add-font (start end type)
140   (let ((overlay (make-overlay start end)))
141     (overlay-put overlay 'face type)))
142
143 (defun shr-tag-a (cont)
144   (let ((url (cdr (assq :href cont)))
145         shr-start)
146     (shr-generic cont)
147     (widget-convert-button
148      'link shr-start (point)
149      :action 'shr-browse-url
150      :url url
151      :keymap widget-keymap
152      :help-echo url)))
153
154 (defun shr-browse-url (widget &rest stuff)
155   (browse-url (widget-get widget :url)))
156
157 (defun shr-tag-img (cont)
158   (when (and (> (current-column) 0)
159              (not (eq shr-state 'image)))
160     (insert "\n"))
161   (let ((start (point-marker)))
162     (let ((alt (cdr (assq :alt cont)))
163           (url (cdr (assq :src cont))))
164       (when (zerop (length alt))
165         (setq alt "[img]"))
166       (cond
167        ((and shr-blocked-images
168              (string-match shr-blocked-images url))
169         (insert alt))
170        ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
171         (shr-put-image (shr-get-image-data url) (point) alt))
172        (t
173         (insert alt)
174         (url-retrieve url 'shr-image-fetched
175                       (list (current-buffer) start (point-marker))
176                       t)))
177       (put-text-property start (point) 'keymap shr-map)
178       (put-text-property start (point) 'shr-alt alt)
179       (put-text-property start (point) 'shr-image url)
180       (insert " ")
181       (setq shr-state 'image))))
182
183 (defun shr-show-alt-text ()
184   "Show the ALT text of the image under point."
185   (interactive)
186   (let ((text (get-text-property (point) 'shr-alt)))
187     (if (not text)
188         (message "No image under point")
189       (message "%s" text))))
190
191 (defun shr-browse-image ()
192   "Browse the image under point."
193   (interactive)
194   (let ((url (get-text-property (point) 'shr-image)))
195     (if (not url)
196         (message "No image under point")
197       (message "Browsing %s..." url)
198       (browse-url url))))
199
200 (defun shr-image-fetched (status buffer start end)
201   (when (and (buffer-name buffer)
202              (not (plist-get status :error)))
203     (url-store-in-cache (current-buffer))
204     (when (or (search-forward "\n\n" nil t)
205               (search-forward "\r\n\r\n" nil t))
206       (let ((data (buffer-substring (point) (point-max))))
207         (with-current-buffer buffer
208           (let ((alt (buffer-substring start end))
209                 (inhibit-read-only t))
210             (delete-region start end)
211             (shr-put-image data start alt))))))
212   (kill-buffer (current-buffer)))
213
214 (defun shr-put-image (data point alt)
215   (if (not (display-graphic-p))
216       (insert alt)
217     (let ((image (ignore-errors
218                    (shr-rescale-image data))))
219       (when image
220         (put-image image point alt)))))
221
222 (defun shr-rescale-image (data)
223   (if (or (not (fboundp 'imagemagick-types))
224           (not (get-buffer-window (current-buffer))))
225       (create-image data nil t)
226     (let* ((image (create-image data nil t))
227            (size (image-size image t))
228            (width (car size))
229            (height (cdr size))
230            (edges (window-inside-pixel-edges
231                    (get-buffer-window (current-buffer))))
232            (window-width (truncate (* shr-max-image-proportion
233                                       (- (nth 2 edges) (nth 0 edges)))))
234            (window-height (truncate (* shr-max-image-proportion
235                                        (- (nth 3 edges) (nth 1 edges)))))
236            scaled-image)
237       (when (> height window-height)
238         (setq image (or (create-image data 'imagemagick t
239                                       :height window-height)
240                         image))
241         (setq size (image-size image t)))
242       (when (> (car size) window-width)
243         (setq image (or
244                      (create-image data 'imagemagick t
245                                    :width window-width)
246                      image)))
247       image)))
248
249 (defun shr-tag-pre (cont)
250   (let ((shr-folding-mode 'none))
251     (shr-ensure-newline)
252     (shr-generic cont)
253     (shr-ensure-newline)))
254
255 (defun shr-tag-blockquote (cont)
256   (shr-ensure-paragraph)
257   (let ((shr-indentation (+ shr-indentation 4)))
258     (shr-generic cont)))
259
260 (defun shr-ensure-newline ()
261   (unless (zerop (current-column))
262     (insert "\n")))
263
264 (defun shr-insert (text)
265   (when (eq shr-state 'image)
266     (insert "\n")
267     (setq shr-state nil))
268   (cond
269    ((eq shr-folding-mode 'none)
270     (insert text))
271    (t
272     (let ((first t)
273           column)
274       (when (and (string-match "\\`[ \t\n]" text)
275                  (not (bolp)))
276         (insert " "))
277       (dolist (elem (split-string text))
278         (setq column (current-column))
279         (when (> column 0)
280           (cond
281            ((and (or (not first)
282                      (eq shr-state 'space))
283                  (> (+ column (length elem) 1) shr-width))
284             (insert "\n"))
285            ((not first)
286             (insert " "))))
287         (setq first nil)
288         (when (and (bolp)
289                    (> shr-indentation 0))
290           (shr-indent))
291         ;; The shr-start is a special variable that is used to pass
292         ;; upwards the first point in the buffer where the text really
293         ;; starts.
294         (unless shr-start
295           (setq shr-start (point)))
296         (insert elem))
297       (setq shr-state nil)
298       (when (and (string-match "[ \t\n]\\'" text)
299                  (not (bolp)))
300         (insert " ")
301         (setq shr-state 'space))))))
302
303 (defun shr-indent ()
304   (insert (make-string shr-indentation ? )))
305
306 (defun shr-get-image-data (url)
307   "Get image data for URL.
308 Return a string with image data."
309   (with-temp-buffer
310     (mm-disable-multibyte)
311     (url-cache-extract (url-cache-create-filename url))
312     (when (or (search-forward "\n\n" nil t)
313               (search-forward "\r\n\r\n" nil t))
314       (buffer-substring (point) (point-max)))))
315
316 (defvar shr-list-mode nil)
317
318 (defun shr-tag-ul (cont)
319   (shr-ensure-paragraph)
320   (let ((shr-list-mode 'ul))
321     (shr-generic cont)))
322
323 (defun shr-tag-ol (cont)
324   (let ((shr-list-mode 1))
325     (shr-generic cont)))
326
327 (defun shr-tag-li (cont)
328   (shr-ensure-newline)
329   (let* ((bullet
330           (if (numberp shr-list-mode)
331               (prog1
332                   (format "%d " shr-list-mode)
333                 (setq shr-list-mode (1+ shr-list-mode)))
334             "* "))
335          (shr-indentation (+ shr-indentation (length bullet))))
336     (insert bullet)
337     (shr-generic cont)))
338
339 (defun shr-tag-br (cont)
340   (unless (bobp)
341     (insert "\n"))
342   (shr-generic cont))
343
344 (defun shr-tag-h1 (cont)
345   (shr-heading cont 'bold 'underline))
346
347 (defun shr-tag-h2 (cont)
348   (shr-heading cont 'bold))
349
350 (defun shr-tag-h3 (cont)
351   (shr-heading cont 'italic))
352
353 (defun shr-tag-h4 (cont)
354   (shr-heading cont))
355
356 (defun shr-tag-h5 (cont)
357   (shr-heading cont))
358
359 (defun shr-tag-h6 (cont)
360   (shr-heading cont))
361
362 (defun shr-heading (cont &rest types)
363   (shr-ensure-paragraph)
364   (apply #'shr-fontize-cont cont types)
365   (shr-ensure-paragraph))
366
367 (defun shr-tag-table (cont)
368   (shr-ensure-paragraph)
369   (setq cont (or (cdr (assq 'tbody cont))
370                  cont))
371   (let* ((columns (shr-column-specs cont))
372          (suggested-widths (shr-pro-rate-columns columns))
373          (sketch (shr-make-table cont suggested-widths))
374          (sketch-widths (shr-table-widths sketch (length suggested-widths))))
375     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths)))
376
377 (defun shr-insert-table (table widths)
378   (shr-insert-table-ruler widths)
379   (dolist (row table)
380     (let ((start (point))
381           (height (let ((max 0))
382                     (dolist (column row)
383                       (setq max (max max (cadr column))))
384                     max)))
385       (dotimes (i height)
386         (shr-indent)
387         (insert "|\n"))
388       (dolist (column row)
389         (goto-char start)
390         (let ((lines (split-string (nth 2 column) "\n")))
391           (dolist (line lines)
392             (when (> (length line) 0)
393               (end-of-line)
394               (insert line "|")
395               (forward-line 1)))
396           ;; Add blank lines at padding at the bottom of the TD,
397           ;; possibly.
398           (dotimes (i (- height (length lines)))
399             (end-of-line)
400             (insert (make-string (length (car lines)) ? ) "|")
401             (forward-line 1)))))
402     (shr-insert-table-ruler widths)))
403
404 (defun shr-insert-table-ruler (widths)
405   (shr-indent)
406   (insert "+")
407   (dotimes (i (length widths))
408     (insert (make-string (aref widths i) ?-) ?+))
409   (insert "\n"))
410
411 (defun shr-table-widths (table length)
412   (let ((widths (make-vector length 0)))
413     (dolist (row table)
414       (let ((i 0))
415         (dolist (column row)
416           (aset widths i (max (aref widths i)
417                               (car column)))
418           (incf i))))
419     widths))
420
421 (defun shr-make-table (cont widths &optional fill)
422   (let ((trs nil))
423     (dolist (row cont)
424       (when (eq (car row) 'tr)
425         (let ((i 0)
426               (tds nil))
427           (dolist (column (cdr row))
428             (when (memq (car column) '(td th))
429               (push (shr-render-td (cdr column) (aref widths i) fill)
430                     tds)
431               (setq i (1+ i))))
432           (push (nreverse tds) trs))))
433     (nreverse trs)))
434
435 (defun shr-render-td (cont width fill)
436   (with-temp-buffer
437     (let ((shr-width width))
438       (shr-generic cont))
439     (while (re-search-backward "\n *$" nil t)
440       (delete-region (match-beginning 0) (match-end 0)))
441     (goto-char (point-min))
442     (let ((max 0))
443       (while (not (eobp))
444         (end-of-line)
445         (setq max (max max (current-column)))
446         (forward-line 1))
447       (when fill
448         (goto-char (point-min))
449         (while (not (eobp))
450           (end-of-line)
451           (insert (make-string (- width (current-column)) ? ))
452           (forward-line 1)))
453       (list max (count-lines (point-min) (point-max)) (buffer-string)))))
454
455 (defun shr-pro-rate-columns (columns)
456   (let ((total-percentage 0)
457         (widths (make-vector (length columns) 0)))
458     (dotimes (i (length columns))
459       (incf total-percentage (aref columns i)))
460     (setq total-percentage (/ 1.0 total-percentage))
461     (dotimes (i (length columns))
462       (aset widths i (max (truncate (* (aref columns i)
463                                        total-percentage
464                                        shr-width))
465                           10)))
466     widths))
467
468 ;; Return a summary of the number and shape of the TDs in the table.
469 (defun shr-column-specs (cont)
470   (let ((columns (make-vector (shr-max-columns cont) 1)))
471     (dolist (row cont)
472       (when (eq (car row) 'tr)
473         (let ((i 0))
474           (dolist (column (cdr row))
475             (when (memq (car column) '(td th))
476               (let ((width (cdr (assq :width (cdr column)))))
477                 (when (and width
478                            (string-match "\\([0-9]+\\)%" width))
479                   (aset columns i
480                         (/ (string-to-number (match-string 1 width))
481                            100.0)))))
482             (setq i (1+ i))))))
483     columns))
484
485 (defun shr-count (cont elem)
486   (let ((i 0))
487     (dolist (sub cont)
488       (when (eq (car sub) elem)
489         (setq i (1+ i))))
490     i))
491
492 (defun shr-max-columns (cont)
493   (let ((max 0))
494     (dolist (row cont)
495       (when (eq (car row) 'tr)
496         (setq max (max max (shr-count (cdr row) 'td)))))
497     max))
498
499 (provide 'shr)
500
501 ;;; shr.el ends here