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