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