(shr-insert): Get white space at the beginning/end of elements right.
[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 (defgroup shr nil
34   "Simple HTML Renderer"
35   :group 'mail)
36
37 (defcustom shr-max-image-proportion 0.9
38   "How big pictures displayed are in relation to the window they're in.
39 A value of 0.7 means that they are allowed to take up 70% of the
40 width and height of the window.  If they are larger than this,
41 and Emacs supports it, then the images will be rescaled down to
42 fit these criteria."
43   :version "24.1"
44   :group 'shr
45   :type 'float)
46
47 (defcustom shr-blocked-images nil
48   "Images that have URLs matching this regexp will be blocked."
49   :version "24.1"
50   :group 'shr
51   :type 'regexp)
52
53 (defvar shr-folding-mode nil)
54 (defvar shr-state nil)
55 (defvar shr-start nil)
56 (defvar shr-indentation 0)
57
58 (defvar shr-width 70)
59
60 (defun shr-transform-dom (dom)
61   (let ((result (list (pop dom))))
62     (dolist (arg (pop dom))
63       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
64                   (cdr arg))
65             result))
66     (dolist (sub dom)
67       (if (stringp sub)
68           (push (cons :text sub) result)
69         (push (shr-transform-dom sub) result)))
70     (nreverse result)))
71
72 ;;;###autoload
73 (defun shr-insert-document (dom)
74   (let ((shr-state nil)
75         (shr-start nil))
76     (shr-descend (shr-transform-dom dom))))
77
78 (defun shr-descend (dom)
79   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
80     (if (fboundp function)
81         (funcall function (cdr dom))
82       (shr-generic (cdr dom)))))
83
84 (defun shr-generic (cont)
85   (dolist (sub cont)
86     (cond
87      ((eq (car sub) :text)
88       (shr-insert (cdr sub)))
89      ((listp (cdr sub))
90       (shr-descend sub)))))
91
92 (defun shr-tag-p (cont)
93   (shr-ensure-paragraph)
94   (shr-generic cont)
95   (unless (bobp)
96     (insert "\n")))
97
98 (defun shr-ensure-paragraph ()
99   (unless (bobp)
100     (if (bolp)
101         (unless (eql (char-after (- (point) 2)) ?\n)
102           (insert "\n"))
103       (insert "\n\n"))))
104
105 (defun shr-tag-b (cont)
106   (shr-fontize-cont cont 'bold))
107
108 (defun shr-tag-i (cont)
109   (shr-fontize-cont cont 'italic))
110
111 (defun shr-tag-u (cont)
112   (shr-fontize-cont cont 'underline))
113
114 (defun shr-s (cont)
115   (shr-fontize-cont cont 'strikethru))
116
117 (defun shr-fontize-cont (cont &rest types)
118   (let (shr-start)
119     (shr-generic cont)
120     (dolist (type types)
121       (shr-add-font (or shr-start (point)) (point) type))))
122
123 (defun shr-add-font (start end type)
124   (let ((overlay (make-overlay start end)))
125     (overlay-put overlay 'face type)))
126
127 (defun shr-tag-a (cont)
128   (let ((url (cdr (assq :href cont)))
129         shr-start)
130     (shr-generic cont)
131     (widget-convert-button
132      'link shr-start (point)
133      :action 'shr-browse-url
134      :url url
135      :keymap widget-keymap
136      :help-echo url)))
137
138 (defun shr-browse-url (widget &rest stuff)
139   (browse-url (widget-get widget :url)))
140
141 (defun shr-tag-img (cont)
142   (when (and (plusp (current-column))
143              (not (eq shr-state 'image)))
144     (insert "\n"))
145   (let ((start (point-marker)))
146     (let ((alt (cdr (assq :alt cont)))
147           (url (cdr (assq :src cont))))
148       (when (zerop (length alt))
149         (setq alt "[img]"))
150       (cond
151        ((and shr-blocked-images
152              (string-match shr-blocked-images url))
153         (insert alt))
154        ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
155         (shr-put-image (shr-get-image-data url) (point) alt))
156        (t
157         (insert alt)
158         (url-retrieve url 'shr-image-fetched
159                       (list (current-buffer) start (point-marker))
160                       t)))
161       (insert " ")
162       (setq shr-state 'image))))
163
164 (defun shr-image-fetched (status buffer start end)
165   (when (and (buffer-name buffer)
166              (not (plist-get status :error)))
167     (url-store-in-cache (current-buffer))
168     (when (or (search-forward "\n\n" nil t)
169               (search-forward "\r\n\r\n" nil t))
170       (let ((data (buffer-substring (point) (point-max))))
171         (with-current-buffer buffer
172           (let ((alt (buffer-substring start end))
173                 (inhibit-read-only t))
174             (delete-region start end)
175             (shr-put-image data start alt))))))
176   (kill-buffer (current-buffer)))
177
178 (defun shr-put-image (data point alt)
179   (if (not (display-graphic-p))
180       (insert alt)
181     (let ((image (ignore-errors
182                    (shr-rescale-image data))))
183       (when image
184         (put-image image point alt)))))
185
186 (defun shr-rescale-image (data)
187   (if (or (not (fboundp 'imagemagick-types))
188           (not (get-buffer-window (current-buffer))))
189       (create-image data nil t)
190     (let* ((image (create-image data nil t))
191            (size (image-size image t))
192            (width (car size))
193            (height (cdr size))
194            (edges (window-inside-pixel-edges
195                    (get-buffer-window (current-buffer))))
196            (window-width (truncate (* shr-max-image-proportion
197                                       (- (nth 2 edges) (nth 0 edges)))))
198            (window-height (truncate (* shr-max-image-proportion
199                                        (- (nth 3 edges) (nth 1 edges)))))
200            scaled-image)
201       (when (> height window-height)
202         (setq image (or (create-image data 'imagemagick t
203                                       :height window-height)
204                         image))
205         (setq size (image-size image t)))
206       (when (> (car size) window-width)
207         (setq image (or
208                      (create-image data 'imagemagick t
209                                    :width window-width)
210                      image)))
211       image)))
212
213 (defun shr-tag-pre (cont)
214   (let ((shr-folding-mode nil))
215     (shr-ensure-newline)
216     (shr-generic cont)
217     (shr-ensure-newline)))
218
219 (defun shr-tag-blockquote (cont)
220   (let ((shr-indentation (+ shr-indentation 4)))
221     (shr-tag-pre cont)))
222
223 (defun shr-ensure-newline ()
224   (unless (zerop (current-column))
225     (insert "\n")))
226
227 (defun shr-insert (text)
228   (when (eq shr-state 'image)
229     (insert "\n")
230     (setq shr-state nil))
231   (cond
232    ((eq shr-folding-mode 'none)
233     (insert t))
234    (t
235     (let ((first t)
236           column)
237       (when (and (string-match "^[ \n]" text)
238                  (not (bolp)))
239         (insert " "))
240       (dolist (elem (split-string text))
241         (setq column (current-column))
242         (when (plusp column)
243           (cond
244            ((> (+ column (length elem) 1) shr-width)
245             (insert "\n"))
246            ((not first)
247             (insert " "))))
248         (setq first nil)
249         (when (and (bolp)
250                    (plusp shr-indentation))
251           (insert (make-string shr-indentation ? )))
252         ;; The shr-start is a special variable that is used to pass
253         ;; upwards the first point in the buffer where the text really
254         ;; starts.
255         (unless shr-start
256           (setq shr-start (point)))
257         (insert elem))
258       (when (and (string-match "[ \n]$" text)
259                  (not (bolp)))
260         (insert " "))))))
261
262 (defun shr-get-image-data (url)
263   "Get image data for URL.
264 Return a string with image data."
265   (with-temp-buffer
266     (mm-disable-multibyte)
267     (url-cache-extract (url-cache-create-filename url))
268     (when (or (search-forward "\n\n" nil t)
269               (search-forward "\r\n\r\n" nil t))
270       (buffer-substring (point) (point-max)))))
271
272 (defvar shr-list-mode nil)
273
274 (defun shr-tag-ul (cont)
275   (shr-ensure-paragraph)
276   (let ((shr-list-mode 'ul))
277     (shr-generic cont)))
278
279 (defun shr-tag-ol (cont)
280   (let ((shr-list-mode 1))
281     (shr-generic cont)))
282
283 (defun shr-tag-li (cont)
284   (shr-ensure-newline)
285   (if (numberp shr-list-mode)
286       (progn
287         (insert (format "%d " shr-list-mode))
288         (setq shr-list-mode (1+ shr-list-mode)))
289     (insert "*"))
290   (shr-generic cont))
291
292 (defun shr-tag-br (cont)
293   (shr-ensure-newline)
294   (shr-generic cont))
295
296 (defun shr-tag-h1 (cont)
297   (shr-heading cont 'bold 'underline))
298
299 (defun shr-tag-h2 (cont)
300   (shr-heading cont 'bold))
301
302 (defun shr-tag-h3 (cont)
303   (shr-heading cont 'italic))
304
305 (defun shr-tag-h4 (cont)
306   (shr-heading cont))
307
308 (defun shr-tag-h5 (cont)
309   (shr-heading cont))
310
311 (defun shr-heading (cont &rest types)
312   (shr-ensure-paragraph)
313   (apply #'shr-fontize-cont cont types)
314   (shr-ensure-paragraph))
315
316 (provide 'shr)
317
318 ;;; shr.el ends here