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