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