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