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