* shr.el: Document the table-rendering algorithm.
[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-content-function nil
56   "If bound, this should be a function that will return the content.
57 This is used for cid: URLs, and the function is called with the
58 cid: URL as the argument.")
59
60 (defvar shr-folding-mode nil)
61 (defvar shr-state nil)
62 (defvar shr-start nil)
63 (defvar shr-indentation 0)
64 (defvar shr-inhibit-images nil)
65
66 (defvar shr-width 70)
67
68 (defvar shr-map
69   (let ((map (make-sparse-keymap)))
70     (define-key map "a" 'shr-show-alt-text)
71     (define-key map "i" 'shr-browse-image)
72     (define-key map "I" 'shr-insert-image)
73     (define-key map "u" 'shr-copy-url)
74     (define-key map "v" 'shr-browse-url)
75     (define-key map "\r" 'shr-browse-url)
76     map))
77
78 (defun shr-transform-dom (dom)
79   (let ((result (list (pop dom))))
80     (dolist (arg (pop dom))
81       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
82                   (cdr arg))
83             result))
84     (dolist (sub dom)
85       (if (stringp sub)
86           (push (cons :text sub) result)
87         (push (shr-transform-dom sub) result)))
88     (nreverse result)))
89
90 ;;;###autoload
91 (defun shr-insert-document (dom)
92   (let ((shr-state nil)
93         (shr-start nil))
94     (shr-descend (shr-transform-dom dom))))
95
96 (defun shr-descend (dom)
97   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
98     (if (fboundp function)
99         (funcall function (cdr dom))
100       (shr-generic (cdr dom)))))
101
102 (defun shr-generic (cont)
103   (dolist (sub cont)
104     (cond
105      ((eq (car sub) :text)
106       (shr-insert (cdr sub)))
107      ((listp (cdr sub))
108       (shr-descend sub)))))
109
110 (defun shr-tag-p (cont)
111   (shr-ensure-paragraph)
112   (shr-generic cont)
113   (shr-ensure-paragraph))
114
115 (defun shr-ensure-paragraph ()
116   (unless (bobp)
117     (if (bolp)
118         (unless (save-excursion
119                   (forward-line -1)
120                   (looking-at " *$"))
121           (insert "\n"))
122       (if (save-excursion
123             (beginning-of-line)
124             (looking-at " *$"))
125           (insert "\n")
126         (insert "\n\n")))))
127
128 (defun shr-tag-b (cont)
129   (shr-fontize-cont cont 'bold))
130
131 (defun shr-tag-i (cont)
132   (shr-fontize-cont cont 'italic))
133
134 (defun shr-tag-em (cont)
135   (shr-fontize-cont cont 'bold))
136
137 (defun shr-tag-u (cont)
138   (shr-fontize-cont cont 'underline))
139
140 (defun shr-tag-s (cont)
141   (shr-fontize-cont cont 'strike-through))
142
143 (defun shr-fontize-cont (cont &rest types)
144   (let (shr-start)
145     (shr-generic cont)
146     (dolist (type types)
147       (shr-add-font (or shr-start (point)) (point) type))))
148
149 (defun shr-add-font (start end type)
150   (let ((overlay (make-overlay start end)))
151     (overlay-put overlay 'face type)))
152
153 (defun shr-tag-a (cont)
154   (let ((url (cdr (assq :href cont)))
155         (start (point))
156         shr-start)
157     (shr-generic cont)
158     (widget-convert-button
159      'link (or shr-start start) (point)
160      :help-echo url)
161     (put-text-property (or shr-start start) (point) 'keymap shr-map)
162     (put-text-property (or shr-start start) (point) 'shr-url url)))
163
164 (defun shr-browse-url ()
165   "Browse the URL under point."
166   (interactive)
167   (let ((url (get-text-property (point) 'shr-url)))
168     (if (not url)
169         (message "No link under point")
170       (browse-url url))))
171
172 (defun shr-copy-url ()
173   "Copy the URL under point to the kill ring.
174 If called twice, then try to fetch the URL and see whether it
175 redirects somewhere else."
176   (interactive)
177   (let ((url (get-text-property (point) 'shr-url)))
178     (cond
179      ((not url)
180       (message "No URL under point"))
181      ;; Resolve redirected URLs.
182      ((equal url (car kill-ring))
183       (url-retrieve
184        url
185        (lambda (a)
186          (when (and (consp a)
187                     (eq (car a) :redirect))
188            (with-temp-buffer
189              (insert (cadr a))
190              (goto-char (point-min))
191              ;; Remove common tracking junk from the URL.
192              (when (re-search-forward ".utm_.*" nil t)
193                (replace-match "" t t))
194              (message "Copied %s" (buffer-string))
195              (copy-region-as-kill (point-min) (point-max)))))))
196      ;; Copy the URL to the kill ring.
197      (t
198       (with-temp-buffer
199         (insert url)
200         (copy-region-as-kill (point-min) (point-max))
201         (message "Copied %s" url))))))
202
203 (defun shr-tag-img (cont)
204   (when (and (> (current-column) 0)
205              (not (eq shr-state 'image)))
206     (insert "\n"))
207   (let ((start (point-marker)))
208     (let ((alt (cdr (assq :alt cont)))
209           (url (cdr (assq :src cont))))
210       (when (zerop (length alt))
211         (setq alt "[img]"))
212       (cond
213        ((and (not shr-inhibit-images)
214              (string-match "\\`cid:" url))
215         (let ((url (substring url (match-end 0)))
216               image)
217           (if (or (not shr-content-function)
218                   (not (setq image (funcall shr-content-function url))))
219               (insert alt)
220             (shr-put-image image (point) alt))))
221        ((or shr-inhibit-images
222             (and shr-blocked-images
223                  (string-match shr-blocked-images url)))
224         (setq shr-start (point))
225         (let ((shr-state 'space))
226           (if (> (length alt) 8)
227               (shr-insert (substring alt 0 8))
228             (shr-insert alt))))
229        ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
230         (shr-put-image (shr-get-image-data url) (point) alt))
231        (t
232         (insert alt)
233         (ignore-errors
234           (url-retrieve url 'shr-image-fetched
235                         (list (current-buffer) start (point-marker))
236                         t))))
237       (insert " ")
238       (put-text-property start (point) 'keymap shr-map)
239       (put-text-property start (point) 'shr-alt alt)
240       (put-text-property start (point) 'shr-image url)
241       (setq shr-state 'image))))
242
243 (defun shr-show-alt-text ()
244   "Show the ALT text of the image under point."
245   (interactive)
246   (let ((text (get-text-property (point) 'shr-alt)))
247     (if (not text)
248         (message "No image under point")
249       (message "%s" text))))
250
251 (defun shr-browse-image ()
252   "Browse the image under point."
253   (interactive)
254   (let ((url (get-text-property (point) 'shr-image)))
255     (if (not url)
256         (message "No image under point")
257       (message "Browsing %s..." url)
258       (browse-url url))))
259
260 (defun shr-image-fetched (status buffer start end)
261   (when (and (buffer-name buffer)
262              (not (plist-get status :error)))
263     (url-store-in-cache (current-buffer))
264     (when (or (search-forward "\n\n" nil t)
265               (search-forward "\r\n\r\n" nil t))
266       (let ((data (buffer-substring (point) (point-max))))
267         (with-current-buffer buffer
268           (let ((alt (buffer-substring start end))
269                 (inhibit-read-only t))
270             (delete-region start end)
271             (shr-put-image data start alt))))))
272   (kill-buffer (current-buffer)))
273
274 (defun shr-put-image (data point alt)
275   (if (not (display-graphic-p))
276       (insert alt)
277     (let ((image (ignore-errors
278                    (shr-rescale-image data))))
279       (when image
280         (put-image image point alt)))))
281
282 (defun shr-rescale-image (data)
283   (if (or (not (fboundp 'imagemagick-types))
284           (not (get-buffer-window (current-buffer))))
285       (create-image data nil t)
286     (let* ((image (create-image data nil t))
287            (size (image-size image t))
288            (width (car size))
289            (height (cdr size))
290            (edges (window-inside-pixel-edges
291                    (get-buffer-window (current-buffer))))
292            (window-width (truncate (* shr-max-image-proportion
293                                       (- (nth 2 edges) (nth 0 edges)))))
294            (window-height (truncate (* shr-max-image-proportion
295                                        (- (nth 3 edges) (nth 1 edges)))))
296            scaled-image)
297       (when (> height window-height)
298         (setq image (or (create-image data 'imagemagick t
299                                       :height window-height)
300                         image))
301         (setq size (image-size image t)))
302       (when (> (car size) window-width)
303         (setq image (or
304                      (create-image data 'imagemagick t
305                                    :width window-width)
306                      image)))
307       image)))
308
309 (defun shr-tag-pre (cont)
310   (let ((shr-folding-mode 'none))
311     (shr-ensure-newline)
312     (shr-generic cont)
313     (shr-ensure-newline)))
314
315 (defun shr-tag-blockquote (cont)
316   (shr-ensure-paragraph)
317   (let ((shr-indentation (+ shr-indentation 4)))
318     (shr-generic cont))
319   (shr-ensure-paragraph))
320
321 (defun shr-ensure-newline ()
322   (unless (zerop (current-column))
323     (insert "\n")))
324
325 (defun shr-insert (text)
326   (when (eq shr-state 'image)
327     (insert "\n")
328     (setq shr-state nil))
329   (cond
330    ((eq shr-folding-mode 'none)
331     (insert text))
332    (t
333     (let ((first t)
334           column)
335       (when (and (string-match "\\`[ \t\n]" text)
336                  (not (bolp)))
337         (insert " "))
338       (dolist (elem (split-string text))
339         (setq column (current-column))
340         (when (> column 0)
341           (cond
342            ((and (or (not first)
343                      (eq shr-state 'space))
344                  (> (+ column (length elem) 1) shr-width))
345             (insert "\n"))
346            ((not first)
347             (insert " "))))
348         (setq first nil)
349         (when (and (bolp)
350                    (> shr-indentation 0))
351           (shr-indent))
352         ;; The shr-start is a special variable that is used to pass
353         ;; upwards the first point in the buffer where the text really
354         ;; starts.
355         (unless shr-start
356           (setq shr-start (point)))
357         (insert elem))
358       (setq shr-state nil)
359       (when (and (string-match "[ \t\n]\\'" text)
360                  (not (bolp)))
361         (insert " ")
362         (setq shr-state 'space))))))
363
364 (defun shr-indent ()
365   (insert (make-string shr-indentation ? )))
366
367 (defun shr-get-image-data (url)
368   "Get image data for URL.
369 Return a string with image data."
370   (with-temp-buffer
371     (mm-disable-multibyte)
372     (when (ignore-errors
373             (url-cache-extract (url-cache-create-filename url))
374             t)
375       (when (or (search-forward "\n\n" nil t)
376                 (search-forward "\r\n\r\n" nil t))
377         (buffer-substring (point) (point-max))))))
378
379 (defvar shr-list-mode nil)
380
381 (defun shr-tag-ul (cont)
382   (shr-ensure-paragraph)
383   (let ((shr-list-mode 'ul))
384     (shr-generic cont)))
385
386 (defun shr-tag-ol (cont)
387   (let ((shr-list-mode 1))
388     (shr-generic cont)))
389
390 (defun shr-tag-li (cont)
391   (shr-ensure-newline)
392   (let* ((bullet
393           (if (numberp shr-list-mode)
394               (prog1
395                   (format "%d " shr-list-mode)
396                 (setq shr-list-mode (1+ shr-list-mode)))
397             "* "))
398          (shr-indentation (+ shr-indentation (length bullet))))
399     (insert bullet)
400     (shr-generic cont)))
401
402 (defun shr-tag-br (cont)
403   (unless (bobp)
404     (insert "\n"))
405   (shr-generic cont))
406
407 (defun shr-tag-h1 (cont)
408   (shr-heading cont 'bold 'underline))
409
410 (defun shr-tag-h2 (cont)
411   (shr-heading cont 'bold))
412
413 (defun shr-tag-h3 (cont)
414   (shr-heading cont 'italic))
415
416 (defun shr-tag-h4 (cont)
417   (shr-heading cont))
418
419 (defun shr-tag-h5 (cont)
420   (shr-heading cont))
421
422 (defun shr-tag-h6 (cont)
423   (shr-heading cont))
424
425 (defun shr-heading (cont &rest types)
426   (shr-ensure-paragraph)
427   (apply #'shr-fontize-cont cont types)
428   (shr-ensure-paragraph))
429
430 ;; Table rendering is the only complicated thing here.  We do this by
431 ;; first counting how many TDs there are in each TR, and registering
432 ;; how wide they think they should be ("width=45%", etc).  Then we
433 ;; render each TD separately (this is done in temporary buffers, so
434 ;; that we can use all the rendering machinery as if we were in the
435 ;; main buffer).  Now we know how much space each TD really takes, so
436 ;; we then render everything again with the new widths, and finally
437 ;; insert all these boxes into the main buffer.
438 (defun shr-tag-table (cont)
439   (shr-ensure-paragraph)
440   (setq cont (or (cdr (assq 'tbody cont))
441                  cont))
442   (let* ((shr-inhibit-images t)
443          ;; Find all suggested widths.
444          (columns (shr-column-specs cont))
445          ;; Compute how many characters wide each TD should be.
446          (suggested-widths (shr-pro-rate-columns columns))
447          ;; Do a "test rendering" to see how big each TD is (this can
448          ;; be smaller (if there's little text) or bigger (if there's
449          ;; unbreakable text).
450          (sketch (shr-make-table cont suggested-widths))
451          (sketch-widths (shr-table-widths sketch (length suggested-widths))))
452     ;; Then render the table again with these new "hard" widths.
453     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
454   ;; Finally, insert all the images after the table.  The Emacs buffer
455   ;; model isn't strong enough to allow us to put the images actually
456   ;; into the tables.
457   (dolist (elem (shr-find-elements cont 'img))
458     (shr-tag-img (cdr elem))))
459
460 (defun shr-find-elements (cont type)
461   (let (result)
462     (dolist (elem cont)
463       (cond ((eq (car elem) type)
464              (push elem result))
465             ((consp (cdr elem))
466              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
467     (nreverse result)))
468
469 (defun shr-insert-table (table widths)
470   (shr-insert-table-ruler widths)
471   (dolist (row table)
472     (let ((start (point))
473           (height (let ((max 0))
474                     (dolist (column row)
475                       (setq max (max max (cadr column))))
476                     max)))
477       (dotimes (i height)
478         (shr-indent)
479         (insert "|\n"))
480       (dolist (column row)
481         (goto-char start)
482         (let ((lines (split-string (nth 2 column) "\n"))
483               (overlay-lines (nth 3 column))
484               overlay overlay-line)
485           (dolist (line lines)
486             (setq overlay-line (pop overlay-lines))
487             (when (> (length line) 0)
488               (end-of-line)
489               (insert line "|")
490               (dolist (overlay overlay-line)
491                 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
492                                        (- (point) (nth 1 overlay) 1)))
493                       (properties (nth 2 overlay)))
494                   (while properties
495                     (overlay-put o (pop properties) (pop properties)))))
496               (forward-line 1)))
497           ;; Add blank lines at padding at the bottom of the TD,
498           ;; possibly.
499           (dotimes (i (- height (length lines)))
500             (end-of-line)
501             (insert (make-string (length (car lines)) ? ) "|")
502             (forward-line 1)))))
503     (shr-insert-table-ruler widths)))
504
505 (defun shr-insert-table-ruler (widths)
506   (shr-indent)
507   (insert "+")
508   (dotimes (i (length widths))
509     (insert (make-string (aref widths i) ?-) ?+))
510   (insert "\n"))
511
512 (defun shr-table-widths (table length)
513   (let ((widths (make-vector length 0)))
514     (dolist (row table)
515       (let ((i 0))
516         (dolist (column row)
517           (aset widths i (max (aref widths i)
518                               (car column)))
519           (incf i))))
520     widths))
521
522 (defun shr-make-table (cont widths &optional fill)
523   (let ((trs nil))
524     (dolist (row cont)
525       (when (eq (car row) 'tr)
526         (let ((tds nil)
527               (columns (cdr row))
528               (i 0)
529               column)
530           (while (< i (length widths))
531             (setq column (pop columns))
532             (when (or (memq (car column) '(td th))
533                       (null column))
534               (push (shr-render-td (cdr column) (aref widths i) fill)
535                     tds)
536               (setq i (1+ i))))
537           (push (nreverse tds) trs))))
538     (nreverse trs)))
539
540 (defun shr-render-td (cont width fill)
541   (with-temp-buffer
542     (let ((shr-width width)
543           (shr-indentation 0))
544       (shr-generic cont))
545     (while (re-search-backward "\n *$" nil t)
546       (delete-region (match-beginning 0) (match-end 0)))
547     (goto-char (point-min))
548     (let ((max 0))
549       (while (not (eobp))
550         (end-of-line)
551         (setq max (max max (current-column)))
552         (forward-line 1))
553       (when fill
554         (goto-char (point-min))
555         ;; If the buffer is totally empty, then put a single blank
556         ;; line here.
557         (if (zerop (buffer-size))
558             (insert (make-string width ? ))
559           ;; Otherwise, fill the buffer.
560           (while (not (eobp))
561             (end-of-line)
562             (when (> (- width (current-column)) 0)
563               (insert (make-string (- width (current-column)) ? )))
564             (forward-line 1))))
565       (list max
566             (count-lines (point-min) (point-max))
567             (buffer-string)
568             (and fill
569                  (shr-collect-overlays))))))
570
571 (defun shr-collect-overlays ()
572   (save-excursion
573     (goto-char (point-min))
574     (let ((overlays nil))
575       (while (not (eobp))
576         (push (shr-overlays-in-region (point) (line-end-position))
577               overlays)
578         (forward-line 1))
579       (nreverse overlays))))
580
581 (defun shr-overlays-in-region (start end)
582   (let (result)
583     (dolist (overlay (overlays-in start end))
584       (push (list (if (> start (overlay-start overlay))
585                       (- end start)
586                     (- end (overlay-start overlay)))
587                   (if (< end (overlay-end overlay))
588                       0
589                     (- end (overlay-end overlay)))
590                   (overlay-properties overlay))
591             result))
592     (nreverse result)))
593
594 (defun shr-pro-rate-columns (columns)
595   (let ((total-percentage 0)
596         (widths (make-vector (length columns) 0)))
597     (dotimes (i (length columns))
598       (incf total-percentage (aref columns i)))
599     (setq total-percentage (/ 1.0 total-percentage))
600     (dotimes (i (length columns))
601       (aset widths i (max (truncate (* (aref columns i)
602                                        total-percentage
603                                        shr-width))
604                           10)))
605     widths))
606
607 ;; Return a summary of the number and shape of the TDs in the table.
608 (defun shr-column-specs (cont)
609   (let ((columns (make-vector (shr-max-columns cont) 1)))
610     (dolist (row cont)
611       (when (eq (car row) 'tr)
612         (let ((i 0))
613           (dolist (column (cdr row))
614             (when (memq (car column) '(td th))
615               (let ((width (cdr (assq :width (cdr column)))))
616                 (when (and width
617                            (string-match "\\([0-9]+\\)%" width))
618                   (aset columns i
619                         (/ (string-to-number (match-string 1 width))
620                            100.0))))
621               (setq i (1+ i)))))))
622     columns))
623
624 (defun shr-count (cont elem)
625   (let ((i 0))
626     (dolist (sub cont)
627       (when (eq (car sub) elem)
628         (setq i (1+ i))))
629     i))
630
631 (defun shr-max-columns (cont)
632   (let ((max 0))
633     (dolist (row cont)
634       (when (eq (car row) 'tr)
635         (setq max (max max (+ (shr-count (cdr row) 'td)
636                               (shr-count (cdr row) 'th))))))
637     max))
638
639 (provide 'shr)
640
641 ;;; shr.el ends here