(gnus-html-wash-tags): Add support for i, b and u HTML tags.
[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
37 (defcustom gnus-html-cache-directory (nnheader-concat gnus-directory "html-cache/")
38   "Where Gnus will cache images it downloads from the web."
39   :version "24.1"
40   :group 'gnus-art
41   :type 'directory)
42
43 (defcustom gnus-html-cache-size 500000000
44   "The size of the Gnus image cache."
45   :version "24.1"
46   :group 'gnus-art
47   :type 'integer)
48
49 (defcustom gnus-html-frame-width 70
50   "What width to use when rendering HTML."
51   :version "24.1"
52   :group 'gnus-art
53   :type 'integer)
54
55 (defcustom gnus-blocked-images "."
56   "Images that have URLs matching this regexp will be blocked."
57   :version "24.1"
58   :group 'gnus-art
59   :type 'regexp)
60
61 (defcustom gnus-max-image-proportion 0.7
62   "How big pictures displayed are in relation to the window they're in.
63 A value of 0.7 means that they are allowed to take up 70% of the
64 width and height of the window.  If they are larger than this,
65 and Emacs supports it, then the images will be rescaled down to
66 fit these criteria."
67   :version "24.1"
68   :group 'gnus-art
69   :type 'float)
70
71 (defvar gnus-html-image-map
72   (let ((map (make-sparse-keymap)))
73     (define-key map "u" 'gnus-article-copy-string)
74     (define-key map "i" 'gnus-html-insert-image)
75     map))
76
77 (defvar gnus-html-displayed-image-map
78   (let ((map (make-sparse-keymap)))
79     (define-key map "a" 'gnus-html-show-alt-text)
80     (define-key map "i" 'gnus-html-browse-image)
81     (define-key map "\r" 'gnus-html-browse-url)
82     (define-key map "u" 'gnus-article-copy-string)
83     (define-key map [tab] 'widget-forward)
84     map))
85
86 ;;;###autoload
87 (defun gnus-article-html (&optional handle)
88   (let ((article-buffer (current-buffer)))
89     (unless handle
90       (setq handle (mm-dissect-buffer t)))
91     (save-restriction
92       (narrow-to-region (point) (point))
93       (save-excursion
94         (mm-with-part handle
95           (let* ((coding-system-for-read 'utf-8)
96                  (coding-system-for-write 'utf-8)
97                  (default-process-coding-system
98                    (cons coding-system-for-read coding-system-for-write))
99                  (charset (mail-content-type-get (mm-handle-type handle)
100                                                  'charset)))
101             (when (and charset
102                        (setq charset (mm-charset-to-coding-system charset))
103                        (not (eq charset 'ascii)))
104               (insert (prog1
105                           (mm-decode-coding-string (buffer-string) charset)
106                         (erase-buffer)
107                         (mm-enable-multibyte))))
108             (call-process-region (point-min) (point-max)
109                                  "w3m"
110                                  nil article-buffer nil
111                                  "-halfdump"
112                                  "-no-cookie"
113                                  "-I" "UTF-8"
114                                  "-O" "UTF-8"
115                                  "-o" "ext_halfdump=1"
116                                  "-o" "pre_conv=1"
117                                  "-t" (format "%s" tab-width)
118                                  "-cols" (format "%s" gnus-html-frame-width)
119                                  "-o" "display_image=on"
120                                  "-T" "text/html"))))
121       (gnus-html-wash-tags))))
122
123 (defvar gnus-article-mouse-face)
124
125 (defun gnus-html-pre-wash ()
126   (goto-char (point-min))
127   (while (re-search-forward " *<pre_int> *</pre_int> *\n" nil t)
128     (replace-match "" t t))
129   (goto-char (point-min))
130   (while (re-search-forward "<a name[^\n>]+>" nil t)
131     (replace-match "" t t)))
132
133 (defun gnus-html-wash-images ()
134   (let (tag parameters string start end images url)
135     (goto-char (point-min))
136     ;; Search for all the images first.
137     (while (re-search-forward "<img_alt \\([^>]*\\)>" nil t)
138       (setq parameters (match-string 1)
139             start (match-beginning 0))
140       (delete-region start (point))
141       (when (search-forward "</img_alt>" (line-end-position) t)
142         (delete-region (match-beginning 0) (match-end 0)))
143       (setq end (point))
144       (when (string-match "src=\"\\([^\"]+\\)" parameters)
145         (setq url (match-string 1 parameters))
146         (gnus-message 8 "gnus-html-wash-tags: fetching image URL %s" url)
147         (if (string-match "^cid:\\(.*\\)" url)
148             ;; URLs with cid: have their content stashed in other
149             ;; parts of the MIME structure, so just insert them
150             ;; immediately.
151             (let ((handle (mm-get-content-id
152                            (setq url (match-string 1 url))))
153                   image)
154               (when handle
155                 (mm-with-part handle
156                   (setq image (gnus-create-image (buffer-string)
157                                                  nil t))))
158               (when image
159                 (let ((string (buffer-substring start end)))
160                   (delete-region start end)
161                   (gnus-put-image image (gnus-string-or string "*") 'cid)
162                   (gnus-add-image 'cid image))))
163           ;; Normal, external URL.
164           (if (gnus-html-image-url-blocked-p
165                url
166                (if (buffer-live-p gnus-summary-buffer)
167                    (with-current-buffer gnus-summary-buffer
168                      gnus-blocked-images)
169                  gnus-blocked-images))
170               (progn
171                 (widget-convert-button
172                  'link start end
173                  :action 'gnus-html-insert-image
174                  :help-echo url
175                  :keymap gnus-html-image-map
176                  :button-keymap gnus-html-image-map)
177                 (let ((overlay (gnus-make-overlay start end))
178                       (spec (list url
179                                   (set-marker (make-marker) start)
180                                   (set-marker (make-marker) end))))
181                   (gnus-overlay-put overlay 'local-map gnus-html-image-map)
182                   (gnus-overlay-put overlay 'gnus-image spec)
183                   (gnus-put-text-property
184                    start end
185                    'gnus-image spec)))
186             (let ((file (gnus-html-image-id url))
187                   width height alt-text)
188               (when (string-match "height=\"?\\([0-9]+\\)" parameters)
189                 (setq height (string-to-number (match-string 1 parameters))))
190               (when (string-match "width=\"?\\([0-9]+\\)" parameters)
191                 (setq width (string-to-number (match-string 1 parameters))))
192               (when (string-match "\\(alt\\|title\\)=\"\\([^\"]+\\)"
193                                   parameters)
194                 (setq alt-text (match-string 2 parameters)))
195               ;; Don't fetch images that are really small.  They're
196               ;; probably tracking pictures.
197               (when (and (or (null height)
198                              (> height 4))
199                          (or (null width)
200                              (> width 4)))
201                 (if (file-exists-p file)
202                     ;; It's already cached, so just insert it.
203                     (let ((string (buffer-substring start end)))
204                       ;; Delete the IMG text.
205                       (delete-region start end)
206                       (gnus-html-put-image file (point) string url alt-text))
207                   ;; We don't have it, so schedule it for fetching
208                   ;; asynchronously.
209                   (push (list url
210                               (set-marker (make-marker) start)
211                               (point-marker))
212                         images))))))))
213     (when images
214       (gnus-html-schedule-image-fetching (current-buffer) (nreverse images)))))
215
216 (defun gnus-html-wash-tags ()
217   (let (tag parameters string start end images url)
218     (gnus-html-pre-wash)
219     (gnus-html-wash-images)
220
221     (goto-char (point-min))
222     ;; Then do the other tags.
223     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
224       (setq tag (match-string 1)
225             parameters (match-string 2)
226             start (match-beginning 0))
227       (when (plusp (length parameters))
228         (set-text-properties 0 (1- (length parameters)) nil parameters))
229       (delete-region start (point))
230       (when (search-forward (concat "</" tag ">") nil t)
231         (delete-region (match-beginning 0) (match-end 0)))
232       (setq end (point))
233       (cond
234        ;; Fetch and insert a picture.
235        ((equal tag "img_alt"))
236        ;; Add a link.
237        ((or (equal tag "a")
238             (equal tag "A"))
239         (when (string-match "href=\"\\([^\"]+\\)" parameters)
240           (setq url (match-string 1 parameters))
241           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
242           (gnus-article-add-button start end
243                                    'browse-url url
244                                    url)
245           (let ((overlay (gnus-make-overlay start end)))
246             (gnus-overlay-put overlay 'evaporate t)
247             (gnus-overlay-put overlay 'gnus-button-url url)
248             (gnus-put-text-property start end 'gnus-string url)
249             (when gnus-article-mouse-face
250               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
251        ;; The upper-case IMG_ALT is apparently just an artifact that
252        ;; should be deleted.
253        ((equal tag "IMG_ALT")
254         (delete-region start end))
255        ;; Whatever.  Just ignore the tag.
256        ((equal tag "b")
257         (gnus-overlay-put (gnus-make-overlay start end) 'face 'bold))
258        ((equal tag "U")
259         (gnus-overlay-put (gnus-make-overlay start end) 'face 'underline))
260        ((equal tag "i")
261         (gnus-overlay-put (gnus-make-overlay start end) 'face 'italic))
262        (t
263         ))
264       (goto-char start))
265     (goto-char (point-min))
266     ;; The output from -halfdump isn't totally regular, so strip
267     ;; off any </pre_int>s that were left over.
268     (while (re-search-forward "</pre_int>\\|</internal>" nil t)
269       (replace-match "" t t))
270     (mm-url-decode-entities)))
271
272 (defun gnus-html-insert-image ()
273   "Fetch and insert the image under point."
274   (interactive)
275   (gnus-html-schedule-image-fetching
276    (current-buffer) (list (get-text-property (point) 'gnus-image))))
277
278 (defun gnus-html-show-alt-text ()
279   "Show the ALT text of the image under point."
280   (interactive)
281   (message "%s" (get-text-property (point) 'gnus-alt-text)))
282
283 (defun gnus-html-browse-image ()
284   "Browse the image under point."
285   (interactive)
286   (browse-url (get-text-property (point) 'gnus-image)))
287
288 (defun gnus-html-browse-url ()
289   "Browse the image under point."
290   (interactive)
291   (let ((url (get-text-property (point) 'gnus-string)))
292     (if (not url)
293         (message "No URL at point")
294       (browse-url url))))
295
296 (defun gnus-html-schedule-image-fetching (buffer images)
297   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, images %s"
298                 buffer images)
299   (when (executable-find "curl")
300     (let* ((url (caar images))
301            (process (start-process
302                      "images" nil "curl"
303                      "-s" "--create-dirs"
304                      "--location"
305                      "--max-time" "60"
306                      "-o" (gnus-html-image-id url)
307                      (mm-url-decode-entities-string url))))
308       (gnus-set-process-query-on-exit-flag process nil)
309       (set-process-sentinel process 'gnus-html-curl-sentinel)
310       (gnus-set-process-plist process (list 'images images
311                                             'buffer buffer)))))
312
313 (defun gnus-html-image-id (url)
314   (expand-file-name (sha1 url) gnus-html-cache-directory))
315
316 (defun gnus-html-curl-sentinel (process event)
317   (when (string-match "finished" event)
318     (let* ((images (gnus-process-get process 'images))
319            (buffer (gnus-process-get process 'buffer))
320            (spec (pop images))
321            (file (gnus-html-image-id (car spec))))
322       (when (and (buffer-live-p buffer)
323                  ;; If the position of the marker is 1, then that
324                  ;; means that the text it was in has been deleted;
325                  ;; i.e., that the user has selected a different
326                  ;; article before the image arrived.
327                  (not (= (marker-position (cadr spec)) (point-min))))
328         (with-current-buffer buffer
329           (let ((inhibit-read-only t)
330                 (string (buffer-substring (cadr spec) (caddr spec))))
331             (delete-region (cadr spec) (caddr spec))
332             (gnus-html-put-image file (cadr spec) string))))
333       (when images
334         (gnus-html-schedule-image-fetching buffer images)))))
335
336 (defun gnus-html-put-image (file point string &optional url alt-text)
337   (when (gnus-graphic-display-p)
338     (let* ((image (ignore-errors
339                    (gnus-create-image file)))
340           (size (and image
341                      (if (featurep 'xemacs)
342                          (cons (glyph-width image) (glyph-height image))
343                        (image-size image t)))))
344       (save-excursion
345         (goto-char point)
346         (if (and image
347                  ;; Kludge to avoid displaying 30x30 gif images, which
348                  ;; seems to be a signal of a broken image.
349                  (not (and (if (featurep 'xemacs)
350                                (glyphp image)
351                              (listp image))
352                            (eq (if (featurep 'xemacs)
353                                    (let ((data (cdadar (specifier-spec-list
354                                                         (glyph-image image)))))
355                                      (and (vectorp data)
356                                           (aref data 0)))
357                                  (plist-get (cdr image) :type))
358                                'gif)
359                            (= (car size) 30)
360                            (= (cdr size) 30))))
361             (let ((start (point)))
362               (setq image (gnus-html-rescale-image image file size))
363               (gnus-put-image image
364                               (gnus-string-or string "*")
365                               'external)
366               (let ((overlay (gnus-make-overlay start (point))))
367                 (gnus-overlay-put overlay 'local-map
368                                   gnus-html-displayed-image-map)
369                 (gnus-put-text-property start (point) 'gnus-alt-text alt-text)
370                 (when url
371                   (gnus-put-text-property start (point) 'gnus-image url)))
372               (gnus-add-image 'external image)
373               t)
374           (insert string)
375           (when (fboundp 'find-image)
376             (setq image (find-image '((:type xpm :file "lock-broken.xpm"))))
377             (gnus-put-image image
378                             (gnus-string-or string "*")
379                             'internal)
380             (gnus-add-image 'internal image))
381           nil)))))
382
383 (defun gnus-html-rescale-image (image file size)
384   (if (or (not (fboundp 'imagemagick-types))
385           (not (get-buffer-window (current-buffer))))
386       image
387     (let* ((width (car size))
388            (height (cdr size))
389            (edges (window-pixel-edges (get-buffer-window (current-buffer))))
390            (window-width (truncate (* gnus-max-image-proportion
391                                       (- (nth 2 edges) (nth 0 edges)))))
392            (window-height (truncate (* gnus-max-image-proportion
393                                        (- (nth 3 edges) (nth 1 edges)))))
394            scaled-image)
395       (when (> height window-height)
396         (setq image (or (create-image file 'imagemagick nil
397                                       :height window-height)
398                         image))
399         (setq size (image-size image t)))
400       (when (> (car size) window-width)
401         (setq image (or
402                      (create-image file 'imagemagick nil
403                                    :width window-width)
404                      image)))
405       image)))
406
407 (defun gnus-html-prune-cache ()
408   (let ((total-size 0)
409         files)
410     (dolist (file (directory-files gnus-html-cache-directory t nil t))
411       (let ((attributes (file-attributes file)))
412         (unless (nth 0 attributes)
413           (incf total-size (nth 7 attributes))
414           (push (list (time-to-seconds (nth 5 attributes))
415                       (nth 7 attributes) file)
416                 files))))
417     (when (> total-size gnus-html-cache-size)
418       (setq files (sort files (lambda (f1 f2)
419                                 (< (car f1) (car f2)))))
420       (dolist (file files)
421         (when (> total-size gnus-html-cache-size)
422           (decf total-size (cadr file))
423           (delete-file (nth 2 file)))))))
424
425 (defun gnus-html-image-url-blocked-p (url blocked-images)
426   "Find out if URL is blocked by BLOCKED-IMAGES."
427   (let ((ret (and blocked-images
428                   (string-match blocked-images url))))
429     (if ret
430         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
431                       url blocked-images)
432       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
433                     url blocked-images))
434     ret))
435
436 (defun gnus-html-show-images ()
437   "Show any images that are in the HTML-rendered article buffer.
438 This only works if the article in question is HTML."
439   (interactive)
440   (gnus-with-article-buffer
441     (let ((overlays (overlays-in (point-min) (point-max)))
442           overlay images)
443       (while (setq overlay (pop overlays))
444         (when (overlay-get overlay 'gnus-image)
445           (push (overlay-get overlay 'gnus-image) images)))
446       (if (not images)
447           (message "No images to show")
448         (gnus-html-schedule-image-fetching (current-buffer) images)))))
449
450 ;;;###autoload
451 (defun gnus-html-prefetch-images (summary)
452   (let (blocked-images urls)
453     (when (and (buffer-live-p summary)
454                (executable-find "curl"))
455       (with-current-buffer summary
456         (setq blocked-images gnus-blocked-images))
457       (save-match-data
458         (while (re-search-forward "<img.*src=[\"']\\([^\"']+\\)" nil t)
459           (let ((url (match-string 1)))
460             (unless (gnus-html-image-url-blocked-p url blocked-images)
461               (unless (file-exists-p (gnus-html-image-id url))
462                 (push (mm-url-decode-entities-string url) urls)
463                 (push (gnus-html-image-id url) urls)
464                 (push "-o" urls)))))
465         (let ((process
466                (apply 'start-process
467                       "images" nil "curl"
468                       "-s" "--create-dirs"
469                       "--location"
470                       "--max-time" "60"
471                       urls)))
472           (gnus-set-process-query-on-exit-flag process nil))))))
473
474 (provide 'gnus-html)
475
476 ;;; gnus-html.el ends here