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