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