Copy over overlays from the TD elements to the main document.
[gnus] / lisp / shr.el
1 ;;; shr.el --- Simple HTML Renderer
2
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: html
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 ;; This package takes a HTML parse tree (as provided by
26 ;; libxml-parse-html-region) and renders it in the current buffer.  It
27 ;; does not do CSS, JavaScript or anything advanced: It's geared
28 ;; towards rendering typical short snippets of HTML, like what you'd
29 ;; find in HTML email and the like.
30
31 ;;; Code:
32
33 (require 'browse-url)
34
35 (defgroup shr nil
36   "Simple HTML Renderer"
37   :group 'mail)
38
39 (defcustom shr-max-image-proportion 0.9
40   "How big pictures displayed are in relation to the window they're in.
41 A value of 0.7 means that they are allowed to take up 70% of the
42 width and height of the window.  If they are larger than this,
43 and Emacs supports it, then the images will be rescaled down to
44 fit these criteria."
45   :version "24.1"
46   :group 'shr
47   :type 'float)
48
49 (defcustom shr-blocked-images nil
50   "Images that have URLs matching this regexp will be blocked."
51   :version "24.1"
52   :group 'shr
53   :type 'regexp)
54
55 (defvar shr-folding-mode nil)
56 (defvar shr-state nil)
57 (defvar shr-start nil)
58 (defvar shr-indentation 0)
59 (defvar shr-inhibit-images nil)
60
61 (defvar shr-width 70)
62
63 (defvar shr-map
64   (let ((map (make-sparse-keymap)))
65     (define-key map "a" 'shr-show-alt-text)
66     (define-key map "i" 'shr-browse-image)
67     (define-key map "I" 'shr-insert-image)
68     (define-key map "u" 'shr-copy-url)
69     (define-key map "v" 'shr-browse-url)
70     (define-key map "\r" 'shr-browse-url)
71     map))
72
73 (defun shr-transform-dom (dom)
74   (let ((result (list (pop dom))))
75     (dolist (arg (pop dom))
76       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
77                   (cdr arg))
78             result))
79     (dolist (sub dom)
80       (if (stringp sub)
81           (push (cons :text sub) result)
82         (push (shr-transform-dom sub) result)))
83     (nreverse result)))
84
85 ;;;###autoload
86 (defun shr-insert-document (dom)
87   (let ((shr-state nil)
88         (shr-start nil))
89     (shr-descend (shr-transform-dom dom))))
90
91 (defun shr-descend (dom)
92   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
93     (if (fboundp function)
94         (funcall function (cdr dom))
95       (shr-generic (cdr dom)))))
96
97 (defun shr-generic (cont)
98   (dolist (sub cont)
99     (cond
100      ((eq (car sub) :text)
101       (shr-insert (cdr sub)))
102      ((listp (cdr sub))
103       (shr-descend sub)))))
104
105 (defun shr-tag-p (cont)
106   (shr-ensure-paragraph)
107   (shr-generic cont)
108   (shr-ensure-paragraph))
109
110 (defun shr-ensure-paragraph ()
111   (unless (bobp)
112     (if (bolp)
113         (unless (save-excursion
114                   (forward-line -1)
115                   (looking-at " *$"))
116           (insert "\n"))
117       (if (save-excursion
118             (beginning-of-line)
119             (looking-at " *$"))
120           (insert "\n")
121         (insert "\n\n")))))
122
123 (defun shr-tag-b (cont)
124   (shr-fontize-cont cont 'bold))
125
126 (defun shr-tag-i (cont)
127   (shr-fontize-cont cont 'italic))
128
129 (defun shr-tag-em (cont)
130   (shr-fontize-cont cont 'bold))
131
132 (defun shr-tag-u (cont)
133   (shr-fontize-cont cont 'underline))
134
135 (defun shr-tag-s (cont)
136   (shr-fontize-cont cont 'strike-through))
137
138 (defun shr-fontize-cont (cont &rest types)
139   (let (shr-start)
140     (shr-generic cont)
141     (dolist (type types)
142       (shr-add-font (or shr-start (point)) (point) type))))
143
144 (defun shr-add-font (start end type)
145   (let ((overlay (make-overlay start end)))
146     (overlay-put overlay 'face type)))
147
148 (defun shr-tag-a (cont)
149   (let ((url (cdr (assq :href cont)))
150         (start (point))
151         shr-start)
152     (shr-generic cont)
153     (widget-convert-button
154      'link (or shr-start start) (point)
155      :help-echo url)
156     (put-text-property (or shr-start start) (point) 'keymap shr-map)
157     (put-text-property (or shr-start start) (point) 'shr-url url)))
158
159 (defun shr-browse-url ()
160   "Browse the URL under point."
161   (interactive)
162   (let ((url (get-text-property (point) 'shr-url)))
163     (if (not url)
164         (message "No link under point")
165       (browse-url url))))
166
167 (defun shr-copy-url ()
168   "Copy the URL under point to the kill ring.
169 If called twice, then try to fetch the URL and see whether it
170 redirects somewhere else."
171   (interactive)
172   (let ((url (get-text-property (point) 'shr-url)))
173     (cond
174      ((not url)
175       (message "No URL under point"))
176      ;; Resolve redirected URLs.
177      ((equal url (car kill-ring))
178       (url-retrieve
179        url
180        (lambda (a)
181          (when (and (consp a)
182                     (eq (car a) :redirect))
183            (with-temp-buffer
184              (insert (cadr a))
185              (goto-char (point-min))
186              ;; Remove common tracking junk from the URL.
187              (when (re-search-forward ".utm_.*" nil t)
188                (replace-match "" t t))
189              (message "Copied %s" (buffer-string))
190              (copy-region-as-kill (point-min) (point-max)))))))
191      ;; Copy the URL to the kill ring.
192      (t
193       (with-temp-buffer
194         (insert url)
195         (copy-region-as-kill (point-min) (point-max))
196         (message "Copied %s" url))))))
197
198 (defun shr-tag-img (cont)
199   (when (and (> (current-column) 0)
200              (not (eq shr-state 'image)))
201     (insert "\n"))
202   (let ((start (point-marker)))
203     (let ((alt (cdr (assq :alt cont)))
204           (url (cdr (assq :src cont))))
205       (when (zerop (length alt))
206         (setq alt "[img]"))
207       (cond
208        ((or shr-inhibit-images
209             (and shr-blocked-images
210                  (string-match shr-blocked-images url)))
211         (setq shr-start (point))
212         (insert alt))
213        ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
214         (shr-put-image (shr-get-image-data url) (point) alt))
215        (t
216         (insert alt)
217         (url-retrieve url 'shr-image-fetched
218                       (list (current-buffer) start (point-marker))
219                       t)))
220       (insert " ")
221       (put-text-property start (point) 'keymap shr-map)
222       (put-text-property start (point) 'shr-alt alt)
223       (put-text-property start (point) 'shr-image url)
224       (setq shr-state 'image))))
225
226 (defun shr-show-alt-text ()
227   "Show the ALT text of the image under point."
228   (interactive)
229   (let ((text (get-text-property (point) 'shr-alt)))
230     (if (not text)
231         (message "No image under point")
232       (message "%s" text))))
233
234 (defun shr-browse-image ()
235   "Browse the image under point."
236   (interactive)
237   (let ((url (get-text-property (point) 'shr-image)))
238     (if (not url)
239         (message "No image under point")
240       (message "Browsing %s..." url)
241       (browse-url url))))
242
243 (defun shr-image-fetched (status buffer start end)
244   (when (and (buffer-name buffer)
245              (not (plist-get status :error)))
246     (url-store-in-cache (current-buffer))
247     (when (or (search-forward "\n\n" nil t)
248               (search-forward "\r\n\r\n" nil t))
249       (let ((data (buffer-substring (point) (point-max))))
250         (with-current-buffer buffer
251           (let ((alt (buffer-substring start end))
252                 (inhibit-read-only t))
253             (delete-region start end)
254             (shr-put-image data start alt))))))
255   (kill-buffer (current-buffer)))
256
257 (defun shr-put-image (data point alt)
258   (if (not (display-graphic-p))
259       (insert alt)
260     (let ((image (ignore-errors
261                    (shr-rescale-image data))))
262       (when image
263         (put-image image point alt)))))
264
265 (defun shr-rescale-image (data)
266   (if (or (not (fboundp 'imagemagick-types))
267           (not (get-buffer-window (current-buffer))))
268       (create-image data nil t)
269     (let* ((image (create-image data nil t))
270            (size (image-size image t))
271            (width (car size))
272            (height (cdr size))
273            (edges (window-inside-pixel-edges
274                    (get-buffer-window (current-buffer))))
275            (window-width (truncate (* shr-max-image-proportion
276                                       (- (nth 2 edges) (nth 0 edges)))))
277            (window-height (truncate (* shr-max-image-proportion
278                                        (- (nth 3 edges) (nth 1 edges)))))
279            scaled-image)
280       (when (> height window-height)
281         (setq image (or (create-image data 'imagemagick t
282                                       :height window-height)
283                         image))
284         (setq size (image-size image t)))
285       (when (> (car size) window-width)
286         (setq image (or
287                      (create-image data 'imagemagick t
288                                    :width window-width)
289                      image)))
290       image)))
291
292 (defun shr-tag-pre (cont)
293   (let ((shr-folding-mode 'none))
294     (shr-ensure-newline)
295     (shr-generic cont)
296     (shr-ensure-newline)))
297
298 (defun shr-tag-blockquote (cont)
299   (shr-ensure-paragraph)
300   (let ((shr-indentation (+ shr-indentation 4)))
301     (shr-generic cont))
302   (shr-ensure-paragraph))
303
304 (defun shr-ensure-newline ()
305   (unless (zerop (current-column))
306     (insert "\n")))
307
308 (defun shr-insert (text)
309   (when (eq shr-state 'image)
310     (insert "\n")
311     (setq shr-state nil))
312   (cond
313    ((eq shr-folding-mode 'none)
314     (insert text))
315    (t
316     (let ((first t)
317           column)
318       (when (and (string-match "\\`[ \t\n]" text)
319                  (not (bolp)))
320         (insert " "))
321       (dolist (elem (split-string text))
322         (setq column (current-column))
323         (when (> column 0)
324           (cond
325            ((and (or (not first)
326                      (eq shr-state 'space))
327                  (> (+ column (length elem) 1) shr-width))
328             (insert "\n"))
329            ((not first)
330             (insert " "))))
331         (setq first nil)
332         (when (and (bolp)
333                    (> shr-indentation 0))
334           (shr-indent))
335         ;; The shr-start is a special variable that is used to pass
336         ;; upwards the first point in the buffer where the text really
337         ;; starts.
338         (unless shr-start
339           (setq shr-start (point)))
340         (insert elem))
341       (setq shr-state nil)
342       (when (and (string-match "[ \t\n]\\'" text)
343                  (not (bolp)))
344         (insert " ")
345         (setq shr-state 'space))))))
346
347 (defun shr-indent ()
348   (insert (make-string shr-indentation ? )))
349
350 (defun shr-get-image-data (url)
351   "Get image data for URL.
352 Return a string with image data."
353   (with-temp-buffer
354     (mm-disable-multibyte)
355     (when (ignore-errors
356             (url-cache-extract (url-cache-create-filename url))
357             t)
358       (when (or (search-forward "\n\n" nil t)
359                 (search-forward "\r\n\r\n" nil t))
360         (buffer-substring (point) (point-max))))))
361
362 (defvar shr-list-mode nil)
363
364 (defun shr-tag-ul (cont)
365   (shr-ensure-paragraph)
366   (let ((shr-list-mode 'ul))
367     (shr-generic cont)))
368
369 (defun shr-tag-ol (cont)
370   (let ((shr-list-mode 1))
371     (shr-generic cont)))
372
373 (defun shr-tag-li (cont)
374   (shr-ensure-newline)
375   (let* ((bullet
376           (if (numberp shr-list-mode)
377               (prog1
378                   (format "%d " shr-list-mode)
379                 (setq shr-list-mode (1+ shr-list-mode)))
380             "* "))
381          (shr-indentation (+ shr-indentation (length bullet))))
382     (insert bullet)
383     (shr-generic cont)))
384
385 (defun shr-tag-br (cont)
386   (unless (bobp)
387     (insert "\n"))
388   (shr-generic cont))
389
390 (defun shr-tag-h1 (cont)
391   (shr-heading cont 'bold 'underline))
392
393 (defun shr-tag-h2 (cont)
394   (shr-heading cont 'bold))
395
396 (defun shr-tag-h3 (cont)
397   (shr-heading cont 'italic))
398
399 (defun shr-tag-h4 (cont)
400   (shr-heading cont))
401
402 (defun shr-tag-h5 (cont)
403   (shr-heading cont))
404
405 (defun shr-tag-h6 (cont)
406   (shr-heading cont))
407
408 (defun shr-heading (cont &rest types)
409   (shr-ensure-paragraph)
410   (apply #'shr-fontize-cont cont types)
411   (shr-ensure-paragraph))
412
413 (defun shr-tag-table (cont)
414   (shr-ensure-paragraph)
415   (setq cont (or (cdr (assq 'tbody cont))
416                  cont))
417   (let* ((shr-inhibit-images t)
418          (columns (shr-column-specs cont))
419          (suggested-widths (shr-pro-rate-columns columns))
420          (sketch (shr-make-table cont suggested-widths))
421          (sketch-widths (shr-table-widths sketch (length suggested-widths))))
422     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
423   (dolist (elem (shr-find-elements cont 'img))
424     (shr-tag-img (cdr elem))))
425
426 (defun shr-find-elements (cont type)
427   (let (result)
428     (dolist (elem cont)
429       (cond ((eq (car elem) type)
430              (push elem result))
431             ((consp (cdr elem))
432              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
433     (nreverse result)))
434
435 (defun shr-insert-table (table widths)
436   (shr-insert-table-ruler widths)
437   (dolist (row table)
438     (let ((start (point))
439           (height (let ((max 0))
440                     (dolist (column row)
441                       (setq max (max max (cadr column))))
442                     max)))
443       (dotimes (i height)
444         (shr-indent)
445         (insert "|\n"))
446       (dolist (column row)
447         (goto-char start)
448         (let ((lines (split-string (nth 2 column) "\n"))
449               (overlay-lines (nth 3 column))
450               overlay)
451           (dolist (line lines)
452             (setq overlay-line (pop overlay-lines))
453             (when (> (length line) 0)
454               (end-of-line)
455               (insert line "|")
456               (dolist (overlay overlay-line)
457                 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
458                                        (- (point) (nth 1 overlay) 1)))
459                       (properties (nth 2 overlay)))
460                   (while properties
461                     (overlay-put o (pop properties) (pop properties)))))
462               (forward-line 1)))
463           ;; Add blank lines at padding at the bottom of the TD,
464           ;; possibly.
465           (dotimes (i (- height (length lines)))
466             (end-of-line)
467             (insert (make-string (length (car lines)) ? ) "|")
468             (forward-line 1)))))
469     (shr-insert-table-ruler widths)))
470
471 (defun shr-insert-table-ruler (widths)
472   (shr-indent)
473   (insert "+")
474   (dotimes (i (length widths))
475     (insert (make-string (aref widths i) ?-) ?+))
476   (insert "\n"))
477
478 (defun shr-table-widths (table length)
479   (let ((widths (make-vector length 0)))
480     (dolist (row table)
481       (let ((i 0))
482         (dolist (column row)
483           (aset widths i (max (aref widths i)
484                               (car column)))
485           (incf i))))
486     widths))
487
488 (defun shr-make-table (cont widths &optional fill)
489   (let ((trs nil))
490     (dolist (row cont)
491       (when (eq (car row) 'tr)
492         (let ((i 0)
493               (tds nil))
494           (dolist (column (cdr row))
495             (when (memq (car column) '(td th))
496               (push (shr-render-td (cdr column) (aref widths i) fill)
497                     tds)
498               (setq i (1+ i))))
499           (push (nreverse tds) trs))))
500     (nreverse trs)))
501
502 (defun shr-render-td (cont width fill)
503   (with-temp-buffer
504     (let ((shr-width width)
505           (shr-indentation 0))
506       (shr-generic cont))
507     (while (re-search-backward "\n *$" nil t)
508       (delete-region (match-beginning 0) (match-end 0)))
509     (goto-char (point-min))
510     (let ((max 0))
511       (while (not (eobp))
512         (end-of-line)
513         (setq max (max max (current-column)))
514         (forward-line 1))
515       (when fill
516         (goto-char (point-min))
517         (while (not (eobp))
518           (end-of-line)
519           (when (> (- width (current-column)) 0)
520             (insert (make-string (- width (current-column)) ? )))
521           (forward-line 1)))
522       (list max
523             (count-lines (point-min) (point-max))
524             (buffer-string)
525             (and fill
526                  (shr-collect-overlays))))))
527
528 (defun shr-collect-overlays ()
529   (save-excursion
530     (goto-char (point-min))
531     (let ((overlays nil))
532       (while (not (eobp))
533         (push (shr-overlays-in-region (point) (line-end-position))
534               overlays)
535         (forward-line 1))
536       (nreverse overlays))))
537
538 (defun shr-overlays-in-region (start end)
539   (let (result)
540     (dolist (overlay (overlays-in start end))
541       (push (list (max start (- end (overlay-start overlay)))
542                   (min end (- end (overlay-end overlay) start))
543                   (overlay-properties overlay))
544             result))
545     (nreverse result)))
546
547 (defun shr-pro-rate-columns (columns)
548   (let ((total-percentage 0)
549         (widths (make-vector (length columns) 0)))
550     (dotimes (i (length columns))
551       (incf total-percentage (aref columns i)))
552     (setq total-percentage (/ 1.0 total-percentage))
553     (dotimes (i (length columns))
554       (aset widths i (max (truncate (* (aref columns i)
555                                        total-percentage
556                                        shr-width))
557                           10)))
558     widths))
559
560 ;; Return a summary of the number and shape of the TDs in the table.
561 (defun shr-column-specs (cont)
562   (let ((columns (make-vector (shr-max-columns cont) 1)))
563     (dolist (row cont)
564       (when (eq (car row) 'tr)
565         (let ((i 0))
566           (dolist (column (cdr row))
567             (when (memq (car column) '(td th))
568               (let ((width (cdr (assq :width (cdr column)))))
569                 (when (and width
570                            (string-match "\\([0-9]+\\)%" width))
571                   (aset columns i
572                         (/ (string-to-number (match-string 1 width))
573                            100.0)))))
574             (setq i (1+ i))))))
575     columns))
576
577 (defun shr-count (cont elem)
578   (let ((i 0))
579     (dolist (sub cont)
580       (when (eq (car sub) elem)
581         (setq i (1+ i))))
582     i))
583
584 (defun shr-max-columns (cont)
585   (let ((max 0))
586     (dolist (row cont)
587       (when (eq (car row) 'tr)
588         (setq max (max max (shr-count (cdr row) 'td)))))
589     max))
590
591 (provide 'shr)
592
593 ;;; shr.el ends here