Allow displaying cid: images from shr.el.
[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         (insert alt))
226        ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
227         (shr-put-image (shr-get-image-data url) (point) alt))
228        (t
229         (insert alt)
230         (url-retrieve url 'shr-image-fetched
231                       (list (current-buffer) start (point-marker))
232                       t)))
233       (insert " ")
234       (put-text-property start (point) 'keymap shr-map)
235       (put-text-property start (point) 'shr-alt alt)
236       (put-text-property start (point) 'shr-image url)
237       (setq shr-state 'image))))
238
239 (defun shr-show-alt-text ()
240   "Show the ALT text of the image under point."
241   (interactive)
242   (let ((text (get-text-property (point) 'shr-alt)))
243     (if (not text)
244         (message "No image under point")
245       (message "%s" text))))
246
247 (defun shr-browse-image ()
248   "Browse the image under point."
249   (interactive)
250   (let ((url (get-text-property (point) 'shr-image)))
251     (if (not url)
252         (message "No image under point")
253       (message "Browsing %s..." url)
254       (browse-url url))))
255
256 (defun shr-image-fetched (status buffer start end)
257   (when (and (buffer-name buffer)
258              (not (plist-get status :error)))
259     (url-store-in-cache (current-buffer))
260     (when (or (search-forward "\n\n" nil t)
261               (search-forward "\r\n\r\n" nil t))
262       (let ((data (buffer-substring (point) (point-max))))
263         (with-current-buffer buffer
264           (let ((alt (buffer-substring start end))
265                 (inhibit-read-only t))
266             (delete-region start end)
267             (shr-put-image data start alt))))))
268   (kill-buffer (current-buffer)))
269
270 (defun shr-put-image (data point alt)
271   (if (not (display-graphic-p))
272       (insert alt)
273     (let ((image (ignore-errors
274                    (shr-rescale-image data))))
275       (when image
276         (put-image image point alt)))))
277
278 (defun shr-rescale-image (data)
279   (if (or (not (fboundp 'imagemagick-types))
280           (not (get-buffer-window (current-buffer))))
281       (create-image data nil t)
282     (let* ((image (create-image data nil t))
283            (size (image-size image t))
284            (width (car size))
285            (height (cdr size))
286            (edges (window-inside-pixel-edges
287                    (get-buffer-window (current-buffer))))
288            (window-width (truncate (* shr-max-image-proportion
289                                       (- (nth 2 edges) (nth 0 edges)))))
290            (window-height (truncate (* shr-max-image-proportion
291                                        (- (nth 3 edges) (nth 1 edges)))))
292            scaled-image)
293       (when (> height window-height)
294         (setq image (or (create-image data 'imagemagick t
295                                       :height window-height)
296                         image))
297         (setq size (image-size image t)))
298       (when (> (car size) window-width)
299         (setq image (or
300                      (create-image data 'imagemagick t
301                                    :width window-width)
302                      image)))
303       image)))
304
305 (defun shr-tag-pre (cont)
306   (let ((shr-folding-mode 'none))
307     (shr-ensure-newline)
308     (shr-generic cont)
309     (shr-ensure-newline)))
310
311 (defun shr-tag-blockquote (cont)
312   (shr-ensure-paragraph)
313   (let ((shr-indentation (+ shr-indentation 4)))
314     (shr-generic cont))
315   (shr-ensure-paragraph))
316
317 (defun shr-ensure-newline ()
318   (unless (zerop (current-column))
319     (insert "\n")))
320
321 (defun shr-insert (text)
322   (when (eq shr-state 'image)
323     (insert "\n")
324     (setq shr-state nil))
325   (cond
326    ((eq shr-folding-mode 'none)
327     (insert text))
328    (t
329     (let ((first t)
330           column)
331       (when (and (string-match "\\`[ \t\n]" text)
332                  (not (bolp)))
333         (insert " "))
334       (dolist (elem (split-string text))
335         (setq column (current-column))
336         (when (> column 0)
337           (cond
338            ((and (or (not first)
339                      (eq shr-state 'space))
340                  (> (+ column (length elem) 1) shr-width))
341             (insert "\n"))
342            ((not first)
343             (insert " "))))
344         (setq first nil)
345         (when (and (bolp)
346                    (> shr-indentation 0))
347           (shr-indent))
348         ;; The shr-start is a special variable that is used to pass
349         ;; upwards the first point in the buffer where the text really
350         ;; starts.
351         (unless shr-start
352           (setq shr-start (point)))
353         (insert elem))
354       (setq shr-state nil)
355       (when (and (string-match "[ \t\n]\\'" text)
356                  (not (bolp)))
357         (insert " ")
358         (setq shr-state 'space))))))
359
360 (defun shr-indent ()
361   (insert (make-string shr-indentation ? )))
362
363 (defun shr-get-image-data (url)
364   "Get image data for URL.
365 Return a string with image data."
366   (with-temp-buffer
367     (mm-disable-multibyte)
368     (when (ignore-errors
369             (url-cache-extract (url-cache-create-filename url))
370             t)
371       (when (or (search-forward "\n\n" nil t)
372                 (search-forward "\r\n\r\n" nil t))
373         (buffer-substring (point) (point-max))))))
374
375 (defvar shr-list-mode nil)
376
377 (defun shr-tag-ul (cont)
378   (shr-ensure-paragraph)
379   (let ((shr-list-mode 'ul))
380     (shr-generic cont)))
381
382 (defun shr-tag-ol (cont)
383   (let ((shr-list-mode 1))
384     (shr-generic cont)))
385
386 (defun shr-tag-li (cont)
387   (shr-ensure-newline)
388   (let* ((bullet
389           (if (numberp shr-list-mode)
390               (prog1
391                   (format "%d " shr-list-mode)
392                 (setq shr-list-mode (1+ shr-list-mode)))
393             "* "))
394          (shr-indentation (+ shr-indentation (length bullet))))
395     (insert bullet)
396     (shr-generic cont)))
397
398 (defun shr-tag-br (cont)
399   (unless (bobp)
400     (insert "\n"))
401   (shr-generic cont))
402
403 (defun shr-tag-h1 (cont)
404   (shr-heading cont 'bold 'underline))
405
406 (defun shr-tag-h2 (cont)
407   (shr-heading cont 'bold))
408
409 (defun shr-tag-h3 (cont)
410   (shr-heading cont 'italic))
411
412 (defun shr-tag-h4 (cont)
413   (shr-heading cont))
414
415 (defun shr-tag-h5 (cont)
416   (shr-heading cont))
417
418 (defun shr-tag-h6 (cont)
419   (shr-heading cont))
420
421 (defun shr-heading (cont &rest types)
422   (shr-ensure-paragraph)
423   (apply #'shr-fontize-cont cont types)
424   (shr-ensure-paragraph))
425
426 (defun shr-tag-table (cont)
427   (shr-ensure-paragraph)
428   (setq cont (or (cdr (assq 'tbody cont))
429                  cont))
430   (let* ((shr-inhibit-images t)
431          (columns (shr-column-specs cont))
432          (suggested-widths (shr-pro-rate-columns columns))
433          (sketch (shr-make-table cont suggested-widths))
434          (sketch-widths (shr-table-widths sketch (length suggested-widths))))
435     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
436   (dolist (elem (shr-find-elements cont 'img))
437     (shr-tag-img (cdr elem))))
438
439 (defun shr-find-elements (cont type)
440   (let (result)
441     (dolist (elem cont)
442       (cond ((eq (car elem) type)
443              (push elem result))
444             ((consp (cdr elem))
445              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
446     (nreverse result)))
447
448 (defun shr-insert-table (table widths)
449   (shr-insert-table-ruler widths)
450   (dolist (row table)
451     (let ((start (point))
452           (height (let ((max 0))
453                     (dolist (column row)
454                       (setq max (max max (cadr column))))
455                     max)))
456       (dotimes (i height)
457         (shr-indent)
458         (insert "|\n"))
459       (dolist (column row)
460         (goto-char start)
461         (let ((lines (split-string (nth 2 column) "\n"))
462               (overlay-lines (nth 3 column))
463               overlay)
464           (dolist (line lines)
465             (setq overlay-line (pop overlay-lines))
466             (when (> (length line) 0)
467               (end-of-line)
468               (insert line "|")
469               (dolist (overlay overlay-line)
470                 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
471                                        (- (point) (nth 1 overlay) 1)))
472                       (properties (nth 2 overlay)))
473                   (while properties
474                     (overlay-put o (pop properties) (pop properties)))))
475               (forward-line 1)))
476           ;; Add blank lines at padding at the bottom of the TD,
477           ;; possibly.
478           (dotimes (i (- height (length lines)))
479             (end-of-line)
480             (insert (make-string (length (car lines)) ? ) "|")
481             (forward-line 1)))))
482     (shr-insert-table-ruler widths)))
483
484 (defun shr-insert-table-ruler (widths)
485   (shr-indent)
486   (insert "+")
487   (dotimes (i (length widths))
488     (insert (make-string (aref widths i) ?-) ?+))
489   (insert "\n"))
490
491 (defun shr-table-widths (table length)
492   (let ((widths (make-vector length 0)))
493     (dolist (row table)
494       (let ((i 0))
495         (dolist (column row)
496           (aset widths i (max (aref widths i)
497                               (car column)))
498           (incf i))))
499     widths))
500
501 (defun shr-make-table (cont widths &optional fill)
502   (let ((trs nil))
503     (dolist (row cont)
504       (when (eq (car row) 'tr)
505         (let ((i 0)
506               (tds nil))
507           (dolist (column (cdr row))
508             (when (memq (car column) '(td th))
509               (push (shr-render-td (cdr column) (aref widths i) fill)
510                     tds)
511               (setq i (1+ i))))
512           (push (nreverse tds) trs))))
513     (nreverse trs)))
514
515 (defun shr-render-td (cont width fill)
516   (with-temp-buffer
517     (let ((shr-width width)
518           (shr-indentation 0))
519       (shr-generic cont))
520     (while (re-search-backward "\n *$" nil t)
521       (delete-region (match-beginning 0) (match-end 0)))
522     (goto-char (point-min))
523     (let ((max 0))
524       (while (not (eobp))
525         (end-of-line)
526         (setq max (max max (current-column)))
527         (forward-line 1))
528       (when fill
529         (goto-char (point-min))
530         (while (not (eobp))
531           (end-of-line)
532           (when (> (- width (current-column)) 0)
533             (insert (make-string (- width (current-column)) ? )))
534           (forward-line 1)))
535       (list max
536             (count-lines (point-min) (point-max))
537             (buffer-string)
538             (and fill
539                  (shr-collect-overlays))))))
540
541 (defun shr-collect-overlays ()
542   (save-excursion
543     (goto-char (point-min))
544     (let ((overlays nil))
545       (while (not (eobp))
546         (push (shr-overlays-in-region (point) (line-end-position))
547               overlays)
548         (forward-line 1))
549       (nreverse overlays))))
550
551 (defun shr-overlays-in-region (start end)
552   (let (result)
553     (dolist (overlay (overlays-in start end))
554       (push (list (max start (- end (overlay-start overlay)))
555                   (min end (- end (overlay-end overlay) start))
556                   (overlay-properties overlay))
557             result))
558     (nreverse result)))
559
560 (defun shr-pro-rate-columns (columns)
561   (let ((total-percentage 0)
562         (widths (make-vector (length columns) 0)))
563     (dotimes (i (length columns))
564       (incf total-percentage (aref columns i)))
565     (setq total-percentage (/ 1.0 total-percentage))
566     (dotimes (i (length columns))
567       (aset widths i (max (truncate (* (aref columns i)
568                                        total-percentage
569                                        shr-width))
570                           10)))
571     widths))
572
573 ;; Return a summary of the number and shape of the TDs in the table.
574 (defun shr-column-specs (cont)
575   (let ((columns (make-vector (shr-max-columns cont) 1)))
576     (dolist (row cont)
577       (when (eq (car row) 'tr)
578         (let ((i 0))
579           (dolist (column (cdr row))
580             (when (memq (car column) '(td th))
581               (let ((width (cdr (assq :width (cdr column)))))
582                 (when (and width
583                            (string-match "\\([0-9]+\\)%" width))
584                   (aset columns i
585                         (/ (string-to-number (match-string 1 width))
586                            100.0))))
587               (setq i (1+ i)))))))
588     columns))
589
590 (defun shr-count (cont elem)
591   (let ((i 0))
592     (dolist (sub cont)
593       (when (eq (car sub) elem)
594         (setq i (1+ i))))
595     i))
596
597 (defun shr-max-columns (cont)
598   (let ((max 0))
599     (dolist (row cont)
600       (when (eq (car row) 'tr)
601         (setq max (max max (+ (shr-count (cdr row) 'td)
602                               (shr-count (cdr row) 'th))))))
603     max))
604
605 (provide 'shr)
606
607 ;;; shr.el ends here