Fix some compilation warnings.
[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   (shr-ensure-paragraph))
96
97 (defun shr-ensure-paragraph ()
98   (unless (bobp)
99     (if (bolp)
100         (unless (eql (char-after (- (point) 2)) ?\n)
101           (insert "\n"))
102       (if (save-excursion
103             (beginning-of-line)
104             (looking-at " *$"))
105           (insert "\n")
106         (insert "\n\n")))))
107
108 (defun shr-tag-b (cont)
109   (shr-fontize-cont cont 'bold))
110
111 (defun shr-tag-i (cont)
112   (shr-fontize-cont cont 'italic))
113
114 (defun shr-tag-u (cont)
115   (shr-fontize-cont cont 'underline))
116
117 (defun shr-tag-s (cont)
118   (shr-fontize-cont cont 'strike-through))
119
120 (defun shr-fontize-cont (cont &rest types)
121   (let (shr-start)
122     (shr-generic cont)
123     (dolist (type types)
124       (shr-add-font (or shr-start (point)) (point) type))))
125
126 (defun shr-add-font (start end type)
127   (let ((overlay (make-overlay start end)))
128     (overlay-put overlay 'face type)))
129
130 (defun shr-tag-a (cont)
131   (let ((url (cdr (assq :href cont)))
132         shr-start)
133     (shr-generic cont)
134     (widget-convert-button
135      'link shr-start (point)
136      :action 'shr-browse-url
137      :url url
138      :keymap widget-keymap
139      :help-echo url)))
140
141 (defun shr-browse-url (widget &rest stuff)
142   (browse-url (widget-get widget :url)))
143
144 (defun shr-tag-img (cont)
145   (when (and (> (current-column) 0)
146              (not (eq shr-state 'image)))
147     (insert "\n"))
148   (let ((start (point-marker)))
149     (let ((alt (cdr (assq :alt cont)))
150           (url (cdr (assq :src cont))))
151       (when (zerop (length alt))
152         (setq alt "[img]"))
153       (cond
154        ((and shr-blocked-images
155              (string-match shr-blocked-images url))
156         (insert alt))
157        ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
158         (shr-put-image (shr-get-image-data url) (point) alt))
159        (t
160         (insert alt)
161         (url-retrieve url 'shr-image-fetched
162                       (list (current-buffer) start (point-marker))
163                       t)))
164       (insert " ")
165       (setq shr-state 'image))))
166
167 (defun shr-image-fetched (status buffer start end)
168   (when (and (buffer-name buffer)
169              (not (plist-get status :error)))
170     (url-store-in-cache (current-buffer))
171     (when (or (search-forward "\n\n" nil t)
172               (search-forward "\r\n\r\n" nil t))
173       (let ((data (buffer-substring (point) (point-max))))
174         (with-current-buffer buffer
175           (let ((alt (buffer-substring start end))
176                 (inhibit-read-only t))
177             (delete-region start end)
178             (shr-put-image data start alt))))))
179   (kill-buffer (current-buffer)))
180
181 (defun shr-put-image (data point alt)
182   (if (not (display-graphic-p))
183       (insert alt)
184     (let ((image (ignore-errors
185                    (shr-rescale-image data))))
186       (when image
187         (put-image image point alt)))))
188
189 (defun shr-rescale-image (data)
190   (if (or (not (fboundp 'imagemagick-types))
191           (not (get-buffer-window (current-buffer))))
192       (create-image data nil t)
193     (let* ((image (create-image data nil t))
194            (size (image-size image t))
195            (width (car size))
196            (height (cdr size))
197            (edges (window-inside-pixel-edges
198                    (get-buffer-window (current-buffer))))
199            (window-width (truncate (* shr-max-image-proportion
200                                       (- (nth 2 edges) (nth 0 edges)))))
201            (window-height (truncate (* shr-max-image-proportion
202                                        (- (nth 3 edges) (nth 1 edges)))))
203            scaled-image)
204       (when (> height window-height)
205         (setq image (or (create-image data 'imagemagick t
206                                       :height window-height)
207                         image))
208         (setq size (image-size image t)))
209       (when (> (car size) window-width)
210         (setq image (or
211                      (create-image data 'imagemagick t
212                                    :width window-width)
213                      image)))
214       image)))
215
216 (defun shr-tag-pre (cont)
217   (let ((shr-folding-mode 'none))
218     (shr-ensure-newline)
219     (shr-generic cont)
220     (shr-ensure-newline)))
221
222 (defun shr-tag-blockquote (cont)
223   (shr-ensure-paragraph)
224   (let ((shr-indentation (+ shr-indentation 4)))
225     (shr-generic cont)))
226
227 (defun shr-ensure-newline ()
228   (unless (zerop (current-column))
229     (insert "\n")))
230
231 (defun shr-insert (text)
232   (when (eq shr-state 'image)
233     (insert "\n")
234     (setq shr-state nil))
235   (cond
236    ((eq shr-folding-mode 'none)
237     (insert text))
238    (t
239     (let ((first t)
240           column)
241       (when (and (string-match "\\`[ \t\n]" text)
242                  (not (bolp)))
243         (insert " "))
244       (dolist (elem (split-string text))
245         (setq column (current-column))
246         (when (> column 0)
247           (cond
248            ((and (or (not first)
249                      (eq shr-state 'space))
250                  (> (+ column (length elem) 1) shr-width))
251             (insert "\n"))
252            ((not first)
253             (insert " "))))
254         (setq first nil)
255         (when (and (bolp)
256                    (> shr-indentation 0))
257           (shr-indent))
258         ;; The shr-start is a special variable that is used to pass
259         ;; upwards the first point in the buffer where the text really
260         ;; starts.
261         (unless shr-start
262           (setq shr-start (point)))
263         (insert elem))
264       (setq shr-state nil)
265       (when (and (string-match "[ \t\n]\\'" text)
266                  (not (bolp)))
267         (insert " ")
268         (setq shr-state 'space))))))
269
270 (defun shr-indent ()
271   (insert (make-string shr-indentation ? )))
272
273 (defun shr-get-image-data (url)
274   "Get image data for URL.
275 Return a string with image data."
276   (with-temp-buffer
277     (mm-disable-multibyte)
278     (url-cache-extract (url-cache-create-filename url))
279     (when (or (search-forward "\n\n" nil t)
280               (search-forward "\r\n\r\n" nil t))
281       (buffer-substring (point) (point-max)))))
282
283 (defvar shr-list-mode nil)
284
285 (defun shr-tag-ul (cont)
286   (shr-ensure-paragraph)
287   (let ((shr-list-mode 'ul))
288     (shr-generic cont)))
289
290 (defun shr-tag-ol (cont)
291   (let ((shr-list-mode 1))
292     (shr-generic cont)))
293
294 (defun shr-tag-li (cont)
295   (shr-ensure-newline)
296   (let* ((bullet
297           (if (numberp shr-list-mode)
298               (prog1
299                   (format "%d " shr-list-mode)
300                 (setq shr-list-mode (1+ shr-list-mode)))
301             "* "))
302          (shr-indentation (+ shr-indentation (length bullet))))
303     (insert bullet)
304     (shr-generic cont)))
305
306 (defun shr-tag-br (cont)
307   (unless (bobp)
308     (insert "\n"))
309   (shr-generic cont))
310
311 (defun shr-tag-h1 (cont)
312   (shr-heading cont 'bold 'underline))
313
314 (defun shr-tag-h2 (cont)
315   (shr-heading cont 'bold))
316
317 (defun shr-tag-h3 (cont)
318   (shr-heading cont 'italic))
319
320 (defun shr-tag-h4 (cont)
321   (shr-heading cont))
322
323 (defun shr-tag-h5 (cont)
324   (shr-heading cont))
325
326 (defun shr-tag-h6 (cont)
327   (shr-heading cont))
328
329 (defun shr-heading (cont &rest types)
330   (shr-ensure-paragraph)
331   (apply #'shr-fontize-cont cont types)
332   (shr-ensure-paragraph))
333
334 (defun shr-tag-table (cont)
335   (shr-ensure-paragraph)
336   (setq cont (or (cdr (assq 'tbody cont))
337                  cont))
338   (let* ((columns (shr-column-specs cont))
339          (suggested-widths (shr-pro-rate-columns columns))
340          (sketch (shr-make-table cont suggested-widths))
341          (sketch-widths (shr-table-widths sketch (length suggested-widths))))
342     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths)))
343
344 (defun shr-insert-table (table widths)
345   (shr-insert-table-ruler widths)
346   (dolist (row table)
347     (let ((start (point))
348           (height (let ((max 0))
349                     (dolist (column row)
350                       (setq max (max max (cadr column))))
351                     max)))
352       (dotimes (i height)
353         (shr-indent)
354         (insert "|\n"))
355       (dolist (column row)
356         (goto-char start)
357         (let ((lines (split-string (nth 2 column) "\n")))
358           (dolist (line lines)
359             (when (> (length line) 0)
360               (end-of-line)
361               (insert line "|")
362               (forward-line 1)))
363           ;; Add blank lines at padding at the bottom of the TD,
364           ;; possibly.
365           (dotimes (i (- height (length lines)))
366             (end-of-line)
367             (insert (make-string (length (car lines)) ? ) "|")
368             (forward-line 1)))))
369     (shr-insert-table-ruler widths)))
370
371 (defun shr-insert-table-ruler (widths)
372   (shr-indent)
373   (insert "+")
374   (dotimes (i (length widths))
375     (insert (make-string (aref widths i) ?-) ?+))
376   (insert "\n"))
377
378 (defun shr-table-widths (table length)
379   (let ((widths (make-vector length 0)))
380     (dolist (row table)
381       (let ((i 0))
382         (dolist (column row)
383           (aset widths i (max (aref widths i)
384                               (car column)))
385           (incf i))))
386     widths))
387
388 (defun shr-make-table (cont widths &optional fill)
389   (let ((trs nil))
390     (dolist (row cont)
391       (when (eq (car row) 'tr)
392         (let ((i 0)
393               (tds nil))
394           (dolist (column (cdr row))
395             (when (memq (car column) '(td th))
396               (push (shr-render-td (cdr column) (aref widths i) fill)
397                     tds)
398               (setq i (1+ i))))
399           (push (nreverse tds) trs))))
400     (nreverse trs)))
401
402 (defun shr-render-td (cont width fill)
403   (with-temp-buffer
404     (let ((shr-width width))
405       (shr-generic cont))
406     (while (re-search-backward "\n *$" nil t)
407       (delete-region (match-beginning 0) (match-end 0)))
408     (goto-char (point-min))
409     (let ((max 0))
410       (while (not (eobp))
411         (end-of-line)
412         (setq max (max max (current-column)))
413         (forward-line 1))
414       (when fill
415         (goto-char (point-min))
416         (while (not (eobp))
417           (end-of-line)
418           (insert (make-string (- width (current-column)) ? ))
419           (forward-line 1)))
420       (list max (count-lines (point-min) (point-max)) (buffer-string)))))
421
422 (defun shr-pro-rate-columns (columns)
423   (let ((total-percentage 0)
424         (widths (make-vector (length columns) 0)))
425     (dotimes (i (length columns))
426       (incf total-percentage (aref columns i)))
427     (setq total-percentage (/ 1.0 total-percentage))
428     (dotimes (i (length columns))
429       (aset widths i (max (truncate (* (aref columns i)
430                                        total-percentage
431                                        shr-width))
432                           10)))
433     widths))
434
435 ;; Return a summary of the number and shape of the TDs in the table.
436 (defun shr-column-specs (cont)
437   (let ((columns (make-vector (shr-max-columns cont) 1)))
438     (dolist (row cont)
439       (when (eq (car row) 'tr)
440         (let ((i 0))
441           (dolist (column (cdr row))
442             (when (memq (car column) '(td th))
443               (let ((width (cdr (assq :width (cdr column)))))
444                 (when (and width
445                            (string-match "\\([0-9]+\\)%" width))
446                   (aset columns i
447                         (/ (string-to-number (match-string 1 width))
448                            100.0)))))
449             (setq i (1+ i))))))
450     columns))
451
452 (defun shr-count (cont elem)
453   (let ((i 0))
454     (dolist (sub cont)
455       (when (eq (car sub) elem)
456         (setq i (1+ i))))
457     i))
458
459 (defun shr-max-columns (cont)
460   (let ((max 0))
461     (dolist (row cont)
462       (when (eq (car row) 'tr)
463         (setq max (max max (shr-count (cdr row) 'td)))))
464     max))
465
466 (provide 'shr)
467
468 ;;; shr.el ends here