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