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