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