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