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