3b9709cc419adab8be83cc12425e189aca90b231
[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       (dolist (elem (split-string text))
180         (setq column (current-column))
181         (when (> column 0)
182           (cond
183            ((and (or (not first)
184                      (eq shr-state 'space))
185                  (> (+ column (length elem) 1) shr-width))
186             (insert "\n"))
187            ((not first)
188             (insert " "))))
189         (setq first nil)
190         (when (and (bolp)
191                    (> shr-indentation 0))
192           (shr-indent))
193         ;; The shr-start is a special variable that is used to pass
194         ;; upwards the first point in the buffer where the text really
195         ;; starts.
196         (unless shr-start
197           (setq shr-start (point)))
198         (insert elem))
199       (setq shr-state nil)
200       (when (and (string-match "[ \t\n]\\'" text)
201                  (not (bolp)))
202         (insert " ")
203         (setq shr-state 'space))))))
204
205 (defun shr-ensure-newline ()
206   (unless (zerop (current-column))
207     (insert "\n")))
208
209 (defun shr-ensure-paragraph ()
210   (unless (bobp)
211     (if (bolp)
212         (unless (save-excursion
213                   (forward-line -1)
214                   (looking-at " *$"))
215           (insert "\n"))
216       (if (save-excursion
217             (beginning-of-line)
218             (looking-at " *$"))
219           (insert "\n")
220         (insert "\n\n")))))
221
222 (defun shr-indent ()
223   (insert (make-string shr-indentation ? )))
224
225 (defun shr-fontize-cont (cont &rest types)
226   (let (shr-start)
227     (shr-generic cont)
228     (dolist (type types)
229       (shr-add-font (or shr-start (point)) (point) type))))
230
231 (defun shr-add-font (start end type)
232   (let ((overlay (make-overlay start end)))
233     (overlay-put overlay 'face type)))
234
235 (defun shr-browse-url ()
236   "Browse the URL under point."
237   (interactive)
238   (let ((url (get-text-property (point) 'shr-url)))
239     (if (not url)
240         (message "No link under point")
241       (browse-url url))))
242
243 (defun shr-image-fetched (status buffer start end)
244   (when (and (buffer-name buffer)
245              (not (plist-get status :error)))
246     (url-store-in-cache (current-buffer))
247     (when (or (search-forward "\n\n" nil t)
248               (search-forward "\r\n\r\n" nil t))
249       (let ((data (buffer-substring (point) (point-max))))
250         (with-current-buffer buffer
251           (let ((alt (buffer-substring start end))
252                 (inhibit-read-only t))
253             (delete-region start end)
254             (shr-put-image data start alt))))))
255   (kill-buffer (current-buffer)))
256
257 (defun shr-put-image (data point alt)
258   (if (not (display-graphic-p))
259       (insert alt)
260     (let ((image (ignore-errors
261                    (shr-rescale-image data))))
262       (when image
263         (put-image image point alt)))))
264
265 (defun shr-rescale-image (data)
266   (if (or (not (fboundp 'imagemagick-types))
267           (not (get-buffer-window (current-buffer))))
268       (create-image data nil t)
269     (let* ((image (create-image data nil t))
270            (size (image-size image t))
271            (width (car size))
272            (height (cdr size))
273            (edges (window-inside-pixel-edges
274                    (get-buffer-window (current-buffer))))
275            (window-width (truncate (* shr-max-image-proportion
276                                       (- (nth 2 edges) (nth 0 edges)))))
277            (window-height (truncate (* shr-max-image-proportion
278                                        (- (nth 3 edges) (nth 1 edges)))))
279            scaled-image)
280       (when (> height window-height)
281         (setq image (or (create-image data 'imagemagick t
282                                       :height window-height)
283                         image))
284         (setq size (image-size image t)))
285       (when (> (car size) window-width)
286         (setq image (or
287                      (create-image data 'imagemagick t
288                                    :width window-width)
289                      image)))
290       image)))
291
292 (defun shr-get-image-data (url)
293   "Get image data for URL.
294 Return a string with image data."
295   (with-temp-buffer
296     (mm-disable-multibyte)
297     (when (ignore-errors
298             (url-cache-extract (url-cache-create-filename url))
299             t)
300       (when (or (search-forward "\n\n" nil t)
301                 (search-forward "\r\n\r\n" nil t))
302         (buffer-substring (point) (point-max))))))
303
304 (defun shr-heading (cont &rest types)
305   (shr-ensure-paragraph)
306   (apply #'shr-fontize-cont cont types)
307   (shr-ensure-paragraph))
308
309 ;;; Tag-specific rendering rules.
310
311 (defun shr-tag-p (cont)
312   (shr-ensure-paragraph)
313   (shr-generic cont)
314   (shr-ensure-paragraph))
315
316 (defun shr-tag-b (cont)
317   (shr-fontize-cont cont 'bold))
318
319 (defun shr-tag-i (cont)
320   (shr-fontize-cont cont 'italic))
321
322 (defun shr-tag-em (cont)
323   (shr-fontize-cont cont 'bold))
324
325 (defun shr-tag-u (cont)
326   (shr-fontize-cont cont 'underline))
327
328 (defun shr-tag-s (cont)
329   (shr-fontize-cont cont 'strike-through))
330
331 (defun shr-tag-a (cont)
332   (let ((url (cdr (assq :href cont)))
333         (start (point))
334         shr-start)
335     (shr-generic cont)
336     (widget-convert-button
337      'link (or shr-start start) (point)
338      :help-echo url)
339     (put-text-property (or shr-start start) (point) 'keymap shr-map)
340     (put-text-property (or shr-start start) (point) 'shr-url url)))
341
342 (defun shr-tag-img (cont)
343   (when (and (> (current-column) 0)
344              (not (eq shr-state 'image)))
345     (insert "\n"))
346   (let ((start (point-marker)))
347     (let ((alt (cdr (assq :alt cont)))
348           (url (cdr (assq :src cont))))