f23acf10b9305058bc96ee220a8aa1eba533cca2
[gnus] / lisp / gnus-html.el
1 ;;; gnus-html.el --- Render HTML in a buffer.
2
3 ;; Copyright (C) 2010-2016 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 (parameters start end url alt-text inhibit-images blocked-images)
178     (if (buffer-live-p gnus-summary-buffer)
179         (with-current-buffer gnus-summary-buffer
180           (setq inhibit-images gnus-inhibit-images
181                 blocked-images (gnus-blocked-images)))
182       (setq inhibit-images gnus-inhibit-images
183             blocked-images (gnus-blocked-images)))
184     (goto-char (point-min))
185     ;; Search for all the images first.
186     (while (re-search-forward "<img_alt \\([^>]*\\)>" nil t)
187       (setq parameters (match-string 1)
188             start (match-beginning 0))
189       (delete-region start (point))
190       (when (search-forward "</img_alt>" (line-end-position) t)
191         (delete-region (match-beginning 0) (match-end 0)))
192       (setq end (point))
193       (when (string-match "src=\"\\([^\"]+\\)" parameters)
194         (gnus-message 8 "gnus-html-wash-tags: fetching image URL %s" url)
195         (setq url (gnus-html-encode-url (match-string 1 parameters))
196               alt-text (when (string-match "\\(alt\\|title\\)=\"\\([^\"]+\\)"
197                                            parameters)
198                          (xml-substitute-special (match-string 2 parameters))))
199         (gnus-add-text-properties
200          start end
201          (list 'image-url url
202                'image-displayer `(lambda (url start end)
203                                    (gnus-html-display-image url start end
204                                                             ,alt-text))
205                'gnus-image (list url start end alt-text)))
206         (widget-convert-button
207          'url-link start (point)
208          :help-echo alt-text
209          :keymap gnus-html-image-map
210          url)
211         (if (string-match "\\`cid:" url)
212             ;; URLs with cid: have their content stashed in other
213             ;; parts of the MIME structure, so just insert them
214             ;; immediately.
215             (let* ((handle (mm-get-content-id (substring url (match-end 0))))
216                    (image (when (and handle
217                                      (not inhibit-images))
218                             (gnus-create-image
219                              (mm-with-part handle (buffer-string))
220                              nil t))))
221               (if image
222                   (gnus-add-image
223                    'cid
224                    (gnus-put-image
225                     (gnus-rescale-image
226                      image (gnus-html-maximum-image-size))
227                     (gnus-string-or (prog1
228                                         (buffer-substring start end)
229                                       (delete-region start end))
230                                     "*")
231                     'cid))
232                 (widget-convert-button
233                  'link start end
234                  :action 'gnus-html-insert-image
235                  :help-echo url
236                  :keymap gnus-html-image-map
237                  :button-keymap gnus-html-image-map)))
238           ;; Normal, external URL.
239           (if (or inhibit-images
240                   (gnus-html-image-url-blocked-p url blocked-images))
241               (widget-convert-button
242                'link start end
243                :action 'gnus-html-insert-image
244                :help-echo url
245                :keymap gnus-html-image-map
246                :button-keymap gnus-html-image-map)
247             ;; Non-blocked url
248             (let ((width
249                    (when (string-match "width=\"?\\([0-9]+\\)" parameters)
250                      (string-to-number (match-string 1 parameters))))
251                   (height
252                    (when (string-match "height=\"?\\([0-9]+\\)" parameters)
253                      (string-to-number (match-string 1 parameters)))))
254               ;; Don't fetch images that are really small.  They're
255               ;; probably tracking pictures.
256               (when (and (or (null height)
257                              (> height 4))
258                          (or (null width)
259                              (> width 4)))
260                 (gnus-html-display-image url start end alt-text)))))))))
261
262 (defun gnus-html-display-image (url start end &optional alt-text)
263   "Display image at URL on text from START to END.
264 Use ALT-TEXT for the image string."
265   (or alt-text (setq alt-text "*"))
266   (if (string-match "\\`cid:" url)
267       (let ((handle (mm-get-content-id (substring url (match-end 0)))))
268         (when handle
269           (gnus-html-put-image (mm-with-part handle (buffer-string))
270                                url alt-text)))
271     (if (gnus-html-cache-expired url gnus-html-image-cache-ttl)
272         ;; We don't have it, so schedule it for fetching
273         ;; asynchronously.
274         (gnus-html-schedule-image-fetching
275          (current-buffer)
276          (list url alt-text))
277       ;; It's already cached, so just insert it.
278       (gnus-html-put-image (gnus-html-get-image-data url) url alt-text))))
279
280 (defun gnus-html-wash-tags ()
281   (let (tag parameters start end url)
282     (gnus-html-pre-wash)
283     (gnus-html-wash-images)
284
285     (goto-char (point-min))
286     ;; Then do the other tags.
287     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
288       (setq tag (match-string 1)
289             parameters (match-string 2)
290             start (match-beginning 0))
291       (when (> (length parameters) 0)
292         (set-text-properties 0 (1- (length parameters)) nil parameters))
293       (delete-region start (point))
294       (when (search-forward (concat "</" tag ">") nil t)
295         (delete-region (match-beginning 0) (match-end 0)))
296       (setq end (point))
297       (cond
298        ;; Fetch and insert a picture.
299        ((equal tag "img_alt"))
300        ;; Add a link.
301        ((or (equal tag "a")
302             (equal tag "A"))
303         (when (string-match "href=\"\\([^\"]+\\)" parameters)
304           (setq url (match-string 1 parameters))
305           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
306           (gnus-article-add-button start end
307                                    'browse-url (mm-url-decode-entities-string url)
308                                    url)
309           (let ((overlay (make-overlay start end)))
310             (overlay-put overlay 'evaporate t)
311             (overlay-put overlay 'gnus-button-url url)
312             (gnus-put-text-property start end 'gnus-string url)
313             (when gnus-article-mouse-face
314               (overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
315        ;; The upper-case IMG_ALT is apparently just an artifact that
316        ;; should be deleted.
317        ((equal tag "IMG_ALT")
318         (delete-region start end))
319        ;; w3m does not normalize the case
320        ((or (equal tag "b")
321             (equal tag "B"))
322         (overlay-put (make-overlay start end) 'face 'gnus-emphasis-bold))
323        ((or (equal tag "u")
324             (equal tag "U"))
325         (overlay-put (make-overlay start end) 'face 'gnus-emphasis-underline))
326        ((or (equal tag "i")
327             (equal tag "I"))
328         (overlay-put (make-overlay start end) 'face 'gnus-emphasis-italic))
329        ((or (equal tag "s")
330             (equal tag "S"))
331         (overlay-put (make-overlay start end) 'face 'gnus-emphasis-strikethru))
332        ((or (equal tag "ins")
333             (equal tag "INS"))
334         (overlay-put (make-overlay start end) 'face 'gnus-emphasis-underline))
335        ;; Handle different UL types
336        ((equal tag "_SYMBOL")
337         (when (string-match "TYPE=\\(.+\\)" parameters)
338           (let ((type (string-to-number (match-string 1 parameters))))
339             (delete-region start end)
340             (cond ((= type 33) (insert " "))
341                   ((= type 34) (insert " "))
342                   ((= type 35) (insert " "))
343                   ((= type 36) (insert " "))
344                   ((= type 37) (insert " "))
345                   ((= type 38) (insert " "))
346                   ((= type 39) (insert " "))
347                   ((= type 40) (insert " "))
348                   ((= type 42) (insert " "))
349                   ((= type 43) (insert " "))
350                   (t (insert " "))))))
351        ;; Whatever.  Just ignore the tag.
352        (t
353         ))
354       (goto-char start))
355     (goto-char (point-min))
356     ;; The output from -halfdump isn't totally regular, so strip
357     ;; off any </pre_int>s that were left over.
358     (while (re-search-forward "</pre_int>\\|</internal>" nil t)
359       (replace-match "" t t))
360     (mm-url-decode-entities)))
361
362 (defun gnus-html-insert-image (&rest args)
363   "Fetch and insert the image under point."
364   (interactive)
365   (apply 'gnus-html-display-image (get-text-property (point) 'gnus-image)))
366
367 (defun gnus-html-show-alt-text ()
368   "Show the ALT text of the image under point."
369   (interactive)
370   (message "%s" (get-text-property (point) 'gnus-alt-text)))
371
372 (defun gnus-html-browse-image ()
373   "Browse the image under point."
374   (interactive)
375   (browse-url (get-text-property (point) 'image-url)))
376
377 (defun gnus-html-browse-url ()
378   "Browse the image under point."
379   (interactive)
380   (let ((url (get-text-property (point) 'gnus-string)))
381     (cond
382      ((not url)
383       (message "No link under point"))
384      ((string-match "^mailto:" url)
385       (gnus-url-mailto url))
386      (t
387       (browse-url url)))))
388
389 (defun gnus-html-schedule-image-fetching (buffer image)
390   "Retrieve IMAGE, and place it into BUFFER on arrival."
391   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, image %s"
392                 buffer image)
393   (if (fboundp 'url-queue-retrieve)
394       (url-queue-retrieve (car image)
395                           'gnus-html-image-fetched
396                           (list buffer image) t t)
397     (ignore-errors
398       (url-retrieve (car image)
399                     'gnus-html-image-fetched
400                     (list buffer image)))))
401
402 (defun gnus-html-image-fetched (status buffer image)
403   "Callback function called when image has been fetched."
404   (unless (plist-get status :error)
405     (when (and (or (search-forward "\n\n" nil t)
406                    (search-forward "\r\n\r\n" nil t))
407                (not (eobp)))
408       (when gnus-html-image-automatic-caching
409         (url-store-in-cache (current-buffer)))
410       (when (buffer-live-p buffer)
411         (let ((data (buffer-substring (point) (point-max))))
412           (with-current-buffer buffer
413             (let ((inhibit-read-only t))
414               (gnus-html-put-image data (car image) (cadr image))))))))
415   (kill-buffer (current-buffer)))
416
417 (defun gnus-html-get-image-data (url)
418   "Get image data for URL.
419 Return a string with image data."
420   (with-temp-buffer
421     (mm-disable-multibyte)
422     (url-cache-extract (url-cache-create-filename url))
423     (when (or (search-forward "\n\n" nil t)
424               (search-forward "\r\n\r\n" nil t))
425       (buffer-substring (point) (point-max)))))
426
427 (defun gnus-html-maximum-image-size ()
428   "Return the maximum size of an image according to `gnus-max-image-proportion'."
429   (let ((edges (gnus-window-inside-pixel-edges
430                 (get-buffer-window (current-buffer)))))
431     ;; (width . height)
432     (cons
433      ;; Aimed width
434      (truncate
435       (* gnus-max-image-proportion
436          (- (nth 2 edges) (nth 0 edges))))
437      ;; Aimed height
438      (truncate (* gnus-max-image-proportion
439                   (- (nth 3 edges) (nth 1 edges)))))))
440
441 ;; Behind display-graphic-p test.
442 (declare-function image-size "image.c" (spec &optional pixels frame))
443
444 (defun gnus-html-put-image (data url &optional alt-text)
445   "Put an image with DATA from URL and optional ALT-TEXT."
446   (when (gnus-graphic-display-p)
447     (let* ((start (text-property-any (point-min) (point-max)
448                                      'image-url url))
449            (end (when start
450                   (next-single-property-change start 'image-url))))
451       ;; Image found?
452       (when start
453         (let* ((image
454                 (ignore-errors
455                   (gnus-create-image data nil t)))
456                (size (and image
457                           (if (featurep 'xemacs)
458                               (cons (glyph-width image) (glyph-height image))
459                             (image-size image t)))))
460           (save-excursion
461             (goto-char start)
462             (let ((alt-text (or alt-text
463                                 (buffer-substring-no-properties start end)))
464                   (inhibit-read-only t))
465               (if (and image
466                        ;; Kludge to avoid displaying 30x30 gif images, which
467                        ;; seems to be a signal of a broken image.
468                        (not (and (if (featurep 'xemacs)
469                                      (glyphp image)
470                                    (listp image))
471                                  (eq (if (featurep 'xemacs)
472                                          (let ((d (cdadar
473                                                    (specifier-spec-list
474                                                     (glyph-image image)))))
475                                            (and (vectorp d)
476                                                 (aref d 0)))
477                                        (plist-get (cdr image) :type))
478                                      'gif)
479                                  (= (car size) 30)
480                                  (= (cdr size) 30))))
481                   ;; Good image, add it!
482                   (let ((image (gnus-rescale-image image (gnus-html-maximum-image-size))))
483                     (delete-region start end)
484                     (gnus-put-image image alt-text 'external)
485                     (widget-convert-button
486                      'url-link start (point)
487                      :help-echo alt-text
488                      :keymap gnus-html-displayed-image-map
489                      url)
490                     (gnus-put-text-property start (point)
491                                             'gnus-alt-text alt-text)
492                     (when url
493                       (gnus-add-text-properties
494                        start (point)
495                        `(image-url
496                          ,url
497                          image-displayer
498                          (lambda (url start end)
499                            (gnus-html-display-image url start end
500                                                     ,alt-text)))))
501                     (gnus-add-image 'external image)
502                     t)
503                 ;; Bad image, try to show something else
504                 (when (fboundp 'find-image)
505                   (delete-region start end)
506                   (setq image (find-image
507                                '((:type xpm :file "lock-broken.xpm"))))
508                   (gnus-put-image image alt-text 'internal)
509                   (gnus-add-image 'internal image))
510                 nil))))))))
511
512 (defun gnus-html-image-url-blocked-p (url blocked-images)
513   "Find out if URL is blocked by BLOCKED-IMAGES."
514   (let ((ret (and blocked-images
515                   (string-match blocked-images url))))
516     (if ret
517         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
518                       url blocked-images)
519       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
520                     url blocked-images))
521     ret))
522
523 ;;;###autoload
524 (defun gnus-html-prefetch-images (summary)
525   (when (buffer-live-p summary)
526     (let (inhibit-images blocked-images)
527       (with-current-buffer summary
528         (setq inhibit-images gnus-inhibit-images
529               blocked-images (gnus-blocked-images)))
530       (save-match-data
531         (while (re-search-forward "<img[^>]+src=[\"']\\(http[^\"']+\\)" nil t)
532           (let ((url (gnus-html-encode-url
533                       (mm-url-decode-entities-string (match-string 1)))))
534             (unless (or inhibit-images
535                         (gnus-html-image-url-blocked-p url blocked-images))
536               (when (gnus-html-cache-expired url gnus-html-image-cache-ttl)
537                 (gnus-html-schedule-image-fetching nil
538                                                    (list url))))))))))
539
540 (provide 'gnus-html)
541
542 ;;; gnus-html.el ends here