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