Fix variable name clobbering from previous patch.
[gnus] / lisp / gnus-html.el
1 ;;; gnus-html.el --- Render HTML in a buffer.
2
3 ;; Copyright (C) 2010  Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: html, web
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 ;; The idea is to provide a simple, fast and pretty minimal way to
26 ;; render HTML (including links and images) in a buffer, based on an
27 ;; external HTML renderer (i.e., w3m).
28
29 ;;; Code:
30
31 (eval-when-compile (require 'cl))
32 (eval-when-compile (require 'mm-decode))
33
34 (require 'gnus-art)
35 (require 'mm-url)
36 (require 'url)
37 (require 'url-cache)
38
39 (defcustom gnus-html-image-cache-ttl (days-to-time 7)
40   "Time in seconds used to cache the image on disk."
41   :version "24.1"
42   :group 'gnus-art
43   :type 'integer)
44
45 (defcustom gnus-html-frame-width 70
46   "What width to use when rendering HTML."
47   :version "24.1"
48   :group 'gnus-art
49   :type 'integer)
50
51 (defcustom gnus-blocked-images "."
52   "Images that have URLs matching this regexp will be blocked."
53   :version "24.1"
54   :group 'gnus-art
55   :type 'regexp)
56
57 (defcustom gnus-max-image-proportion 0.7
58   "How big pictures displayed are in relation to the window they're in.
59 A value of 0.7 means that they are allowed to take up 70% of the
60 width and height of the window.  If they are larger than this,
61 and Emacs supports it, then the images will be rescaled down to
62 fit these criteria."
63   :version "24.1"
64   :group 'gnus-art
65   :type 'float)
66
67 (defvar gnus-html-image-map
68   (let ((map (make-sparse-keymap)))
69     (define-key map "u" 'gnus-article-copy-string)
70     (define-key map "i" 'gnus-html-insert-image)
71     (define-key map "v" 'gnus-html-browse-url)
72     map))
73
74 (defvar gnus-html-displayed-image-map
75   (let ((map (make-sparse-keymap)))
76     (define-key map "a" 'gnus-html-show-alt-text)
77     (define-key map "i" 'gnus-html-browse-image)
78     (define-key map "\r" 'gnus-html-browse-url)
79     (define-key map "u" 'gnus-article-copy-string)
80     (define-key map [tab] 'widget-forward)
81     map))
82
83 (defun gnus-html-cache-expired (url ttl)
84   "Check if URL is cached for more than TTL."
85   (cond (url-standalone-mode
86          (not (file-exists-p (url-cache-create-filename url))))
87         (t (let ((cache-time (url-is-cached url)))
88              (if cache-time
89                  (time-less-p
90                   (time-add
91                    cache-time
92                    ttl)
93                   (current-time))
94                t)))))
95
96 ;;;###autoload
97 (defun gnus-article-html (&optional handle)
98   (let ((article-buffer (current-buffer)))
99     (unless handle
100       (setq handle (mm-dissect-buffer t)))
101     (save-restriction
102       (narrow-to-region (point) (point))
103       (save-excursion
104         (mm-with-part handle
105           (let* ((coding-system-for-read 'utf-8)
106                  (coding-system-for-write 'utf-8)
107                  (default-process-coding-system
108                    (cons coding-system-for-read coding-system-for-write))
109                  (charset (mail-content-type-get (mm-handle-type handle)
110                                                  'charset)))
111             (when (and charset
112                        (setq charset (mm-charset-to-coding-system charset))
113                        (not (eq charset 'ascii)))
114               (insert (prog1
115                           (mm-decode-coding-string (buffer-string) charset)
116                         (erase-buffer)
117                         (mm-enable-multibyte))))
118             (call-process-region (point-min) (point-max)
119                                  "w3m"
120                                  nil article-buffer nil
121                                  "-halfdump"
122                                  "-no-cookie"
123                                  "-I" "UTF-8"
124                                  "-O" "UTF-8"
125                                  "-o" "ext_halfdump=1"
126                                  "-o" "display_ins_del=2"
127                                  "-o" "pre_conv=1"
128                                  "-t" (format "%s" tab-width)
129                                  "-cols" (format "%s" gnus-html-frame-width)
130                                  "-o" "display_image=on"
131                                  "-T" "text/html"))))
132       (gnus-html-wash-tags))))
133
134 (defvar gnus-article-mouse-face)
135
136 (defun gnus-html-pre-wash ()
137   (goto-char (point-min))
138   (while (re-search-forward " *<pre_int> *</pre_int> *\n" nil t)
139     (replace-match "" t t))
140   (goto-char (point-min))
141   (while (re-search-forward "<a name[^\n>]+>" nil t)
142     (replace-match "" t t)))
143
144 (defun gnus-html-wash-images ()
145   "Run through current buffer and replace img tags by images."
146   (let (tag parameters string start end images url)
147     (goto-char (point-min))
148     ;; Search for all the images first.
149     (while (re-search-forward "<img_alt \\([^>]*\\)>" nil t)
150       (setq parameters (match-string 1)
151             start (match-beginning 0))
152       (delete-region start (point))
153       (when (search-forward "</img_alt>" (line-end-position) t)
154         (delete-region (match-beginning 0) (match-end 0)))
155       (setq end (point))
156       (when (string-match "src=\"\\([^\"]+\\)" parameters)
157         (setq url (match-string 1 parameters))
158         (gnus-message 8 "gnus-html-wash-tags: fetching image URL %s" url)
159         (if (string-match "^cid:\\(.*\\)" url)
160             ;; URLs with cid: have their content stashed in other
161             ;; parts of the MIME structure, so just insert them
162             ;; immediately.
163             (let ((handle (mm-get-content-id
164                            (setq url (match-string 1 url))))
165                   image)
166               (when handle
167                 (mm-with-part handle
168                   (setq image (gnus-create-image (buffer-string)
169                                                  nil t))))
170               (when image
171                 (let ((string (buffer-substring start end)))
172                   (delete-region start end)
173                   (gnus-put-image image (gnus-string-or string "*") 'cid)
174                   (gnus-add-image 'cid image))))
175           ;; Normal, external URL.
176           (let ((alt-text (when (string-match "\\(alt\\|title\\)=\"\\([^\"]+\\)"
177                                               parameters)
178                             (match-string 2 parameters))))
179             (if (gnus-html-image-url-blocked-p
180                  url
181                  (if (buffer-live-p gnus-summary-buffer)
182                      (with-current-buffer gnus-summary-buffer
183                        gnus-blocked-images)
184                    gnus-blocked-images))
185                 (progn
186                   (widget-convert-button
187                    'link start end
188                    :action 'gnus-html-insert-image
189                    :help-echo url
190                    :keymap gnus-html-image-map
191                    :button-keymap gnus-html-image-map)
192                   (let ((overlay (gnus-make-overlay start end))
193                         (spec (list url
194                                     (set-marker (make-marker) start)
195                                     (set-marker (make-marker) end)
196                                     alt-text)))
197                     (gnus-overlay-put overlay 'local-map gnus-html-image-map)
198                     (gnus-overlay-put overlay 'gnus-image spec)
199                     (gnus-put-text-property start end 'gnus-image-url url)
200                     (gnus-put-text-property
201                      start end
202                      'gnus-image spec)))
203               ;; Non-blocked url
204               (let ((width
205                      (when (string-match "width=\"?\\([0-9]+\\)" parameters)
206                        (string-to-number (match-string 1 parameters))))
207                     (height
208                      (when (string-match "height=\"?\\([0-9]+\\)" parameters)
209                        (string-to-number (match-string 1 parameters)))))
210                 ;; Don't fetch images that are really small.  They're
211                 ;; probably tracking pictures.
212                 (when (and (or (null height)
213                                (> height 4))
214                            (or (null width)
215                                (> width 4)))
216                   (gnus-html-display-image url start end alt-text))))))))))
217
218 (defun gnus-html-display-image (url start end alt-text)
219   "Display image at URL on text from START to END.
220 Use ALT-TEXT for the image string."
221   (if (gnus-html-cache-expired url gnus-html-image-cache-ttl)
222       ;; We don't have it, so schedule it for fetching
223       ;; asynchronously.
224       (gnus-html-schedule-image-fetching
225        (current-buffer)
226        (list url
227              (set-marker (make-marker) start)
228              (set-marker (make-marker) end)
229              alt-text))
230     ;; It's already cached, so just insert it.
231     (gnus-html-put-image (gnus-html-get-image-data url)
232                          start end url alt-text)))
233
234 (defun gnus-html-wash-tags ()
235   (let (tag parameters string start end images url)
236     (gnus-html-pre-wash)
237     (gnus-html-wash-images)
238
239     (goto-char (point-min))
240     ;; Then do the other tags.
241     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
242       (setq tag (match-string 1)
243             parameters (match-string 2)
244             start (match-beginning 0))
245       (when (plusp (length parameters))
246         (set-text-properties 0 (1- (length parameters)) nil parameters))
247       (delete-region start (point))
248       (when (search-forward (concat "</" tag ">") nil t)
249         (delete-region (match-beginning 0) (match-end 0)))
250       (setq end (point))
251       (cond
252        ;; Fetch and insert a picture.
253        ((equal tag "img_alt"))
254        ;; Add a link.
255        ((or (equal tag "a")
256             (equal tag "A"))
257         (when (string-match "href=\"\\([^\"]+\\)" parameters)
258           (setq url (match-string 1 parameters))
259           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
260           (gnus-article-add-button start end
261                                    'browse-url url
262                                    url)
263           (let ((overlay (gnus-make-overlay start end)))
264             (gnus-overlay-put overlay 'evaporate t)
265             (gnus-overlay-put overlay 'gnus-button-url url)
266             (gnus-put-text-property start end 'gnus-string url)
267             (when gnus-article-mouse-face
268               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
269        ;; The upper-case IMG_ALT is apparently just an artifact that
270        ;; should be deleted.
271        ((equal tag "IMG_ALT")
272         (delete-region start end))
273        ;; w3m does not normalize the case
274        ((or (equal tag "b")
275             (equal tag "B"))
276         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-bold))
277        ((or (equal tag "u")
278             (equal tag "U"))
279         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
280        ((or (equal tag "i")
281             (equal tag "I"))
282         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-italic))
283        ((or (equal tag "s")
284             (equal tag "S"))
285         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-strikethru))
286        ((or (equal tag "ins")
287             (equal tag "INS"))
288         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
289        ;; Handle different UL types
290        ((equal tag "_SYMBOL")
291         (when (string-match "TYPE=\\(.+\\)" parameters)
292           (let ((type (string-to-number (match-string 1 parameters))))
293             (delete-region start end)
294             (cond ((= type 33) (insert " "))
295                   ((= type 34) (insert " "))
296                   ((= type 35) (insert " "))
297                   ((= type 36) (insert " "))
298                   ((= type 37) (insert " "))
299                   ((= type 38) (insert " "))
300                   ((= type 39) (insert " "))
301                   ((= type 40) (insert " "))
302                   ((= type 42) (insert " "))
303                   ((= type 43) (insert " "))
304                   (t (insert " "))))))
305        ;; Whatever.  Just ignore the tag.
306        (t
307         ))
308       (goto-char start))
309     (goto-char (point-min))
310     ;; The output from -halfdump isn't totally regular, so strip
311     ;; off any </pre_int>s that were left over.
312     (while (re-search-forward "</pre_int>\\|</internal>" nil t)
313       (replace-match "" t t))
314     (mm-url-decode-entities)))
315
316 (defun gnus-html-insert-image ()
317   "Fetch and insert the image under point."
318   (interactive)
319   (apply 'gnus-html-display-image (get-text-property (point) 'gnus-image)))
320
321 (defun gnus-html-show-alt-text ()
322   "Show the ALT text of the image under point."
323   (interactive)
324   (message "%s" (get-text-property (point) 'gnus-alt-text)))
325
326 (defun gnus-html-browse-image ()
327   "Browse the image under point."
328   (interactive)
329   (browse-url (get-text-property (point) 'gnus-image-url)))
330
331 (defun gnus-html-browse-url ()
332   "Browse the image under point."
333   (interactive)
334   (let ((url (get-text-property (point) 'gnus-string)))
335     (if (not url)
336         (message "No URL at point")
337       (browse-url url))))
338
339 (defun gnus-html-schedule-image-fetching (buffer image)
340   "Retrieve IMAGE, and place it into BUFFER on arrival."
341   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, image %s"
342                 buffer image)
343   (ignore-errors
344     (url-retrieve (car image)
345                   'gnus-html-image-fetched
346                   (list buffer image))))
347
348 (defun gnus-html-image-fetched (status buffer image)
349   (url-store-in-cache (current-buffer))
350   (when (and (search-forward "\n\n" nil t)
351              (buffer-live-p buffer)
352              ;; If the `image' has no marker, do not replace anything
353              (cadr image)
354              ;; If the position of the marker is 1, then that
355              ;; means that the text it was in has been deleted;
356              ;; i.e., that the user has selected a different
357              ;; article before the image arrived.
358              (not (= (marker-position (cadr image))
359                      (with-current-buffer buffer
360                        (point-min)))))
361     (let ((data (buffer-substring (point) (point-max))))
362       (with-current-buffer buffer
363         (let ((inhibit-read-only t))
364           (gnus-html-put-image data (cadr image) (caddr image) (car image) (cadddr image))))))
365   (kill-buffer (current-buffer)))
366
367 (defun gnus-html-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     (url-cache-extract (url-cache-create-filename url))
373     (when (search-forward "\n\n" nil t)
374       (buffer-substring (point) (point-max)))))
375
376 (defun gnus-html-put-image (data start end &optional url alt-text)
377   (when (gnus-graphic-display-p)
378     (let* ((image (ignore-errors
379                     (gnus-create-image data nil t)))
380            (size (and image
381                       (if (featurep 'xemacs)
382                           (cons (glyph-width image) (glyph-height image))
383                         (image-size image t)))))
384       (save-excursion
385         (goto-char start)
386         (let ((alt-text (or alt-text (buffer-substring-no-properties start end))))
387           (if (and image
388                    ;; Kludge to avoid displaying 30x30 gif images, which
389                    ;; seems to be a signal of a broken image.
390                    (not (and (if (featurep 'xemacs)
391                                  (glyphp image)
392                                (listp image))
393                              (eq (if (featurep 'xemacs)
394                                      (let ((d (cdadar (specifier-spec-list
395                                                        (glyph-image image)))))
396                                        (and (vectorp d)
397                                             (aref d 0)))
398                                    (plist-get (cdr image) :type))
399                                  'gif)
400                              (= (car size) 30)
401                              (= (cdr size) 30))))
402               ;; Good image, add it!
403               (let ((image (gnus-html-rescale-image image data size)))
404                 (delete-region start end)
405                 (gnus-put-image image alt-text 'external)
406                 (gnus-overlay-put (gnus-make-overlay start (point)) 'local-map
407                                   gnus-html-displayed-image-map)
408                 (gnus-put-text-property start (point) 'gnus-alt-text alt-text)
409                 (when url
410                   (gnus-put-text-property start (point) 'gnus-image-url url))
411                 (gnus-add-image 'external image)
412                 t)
413             ;; Bad image, try to show something else
414             (delete-region start end)
415             (when (fboundp 'find-image)
416               (setq image (find-image '((:type xpm :file "lock-broken.xpm"))))
417               (gnus-put-image image alt-text 'internal)
418               (gnus-add-image 'internal image))
419             nil))))))
420
421 (defun gnus-html-rescale-image (image data size)
422   (if (or (not (fboundp 'imagemagick-types))
423           (not (get-buffer-window (current-buffer))))
424       image
425     (let* ((width (car size))
426            (height (cdr size))
427            (edges (window-pixel-edges (get-buffer-window (current-buffer))))
428            (window-width (truncate (* gnus-max-image-proportion
429                                       (- (nth 2 edges) (nth 0 edges)))))
430            (window-height (truncate (* gnus-max-image-proportion
431                                        (- (nth 3 edges) (nth 1 edges)))))
432            scaled-image)
433       (when (> height window-height)
434         (setq image (or (create-image data 'imagemagick t
435                                       :height window-height)
436                         image))
437         (setq size (image-size image t)))
438       (when (> (car size) window-width)
439         (setq image (or
440                      (create-image data 'imagemagick t
441                                    :width window-width)
442                      image)))
443       image)))
444
445 (defun gnus-html-image-url-blocked-p (url blocked-images)
446   "Find out if URL is blocked by BLOCKED-IMAGES."
447   (let ((ret (and blocked-images
448                   (string-match blocked-images url))))
449     (if ret
450         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
451                       url blocked-images)
452       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
453                     url blocked-images))
454     ret))
455
456 (defun gnus-html-show-images ()
457   "Show any images that are in the HTML-rendered article buffer.
458 This only works if the article in question is HTML."
459   (interactive)
460   (gnus-with-article-buffer
461     (dolist (overlay (overlays-in (point-min) (point-max)))
462       (let ((o (overlay-get overlay 'gnus-image)))
463         (when o
464           (apply 'gnus-html-display-image o))))))
465
466 ;;;###autoload
467 (defun gnus-html-prefetch-images (summary)
468   (when (buffer-live-p summary)
469     (let ((blocked-images (with-current-buffer summary
470                             gnus-blocked-images)))
471       (save-match-data
472         (while (re-search-forward "<img.*src=[\"']\\([^\"']+\\)" nil t)
473           (let ((url (match-string 1)))
474             (unless (gnus-html-image-url-blocked-p url blocked-images)
475               (when (gnus-html-cache-expired url gnus-html-image-cache-ttl)
476                 (gnus-html-schedule-image-fetching nil
477                                                    (list url))))))))))
478
479 (provide 'gnus-html)
480
481 ;;; gnus-html.el ends here