9acb557ec6e0e58740c121f4af753310ea068267
[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-content-function nil
56   "If bound, this should be a function that will return the content.
57 This is used for cid: URLs, and the function is called with the
58 cid: URL as the argument.")
59
60 (defvar shr-width 70
61   "Frame width to use for rendering.")
62
63 ;;; Internal variables.
64
65 (defvar shr-folding-mode nil)
66 (defvar shr-state nil)
67 (defvar shr-start nil)
68 (defvar shr-indentation 0)
69 (defvar shr-inhibit-images nil)
70 (defvar shr-list-mode nil)
71 (defvar shr-content-cache nil)
72
73 (defvar shr-map
74   (let ((map (make-sparse-keymap)))
75     (define-key map "a" 'shr-show-alt-text)
76     (define-key map "i" 'shr-browse-image)
77     (define-key map "I" 'shr-insert-image)
78     (define-key map "u" 'shr-copy-url)
79     (define-key map "v" 'shr-browse-url)
80     (define-key map "\r" 'shr-browse-url)
81     map))
82
83 ;; Public functions and commands.
84
85 ;;;###autoload
86 (defun shr-insert-document (dom)
87   (setq shr-content-cache nil)
88   (let ((shr-state nil)
89         (shr-start nil))
90     (shr-descend (shr-transform-dom dom))))
91
92 (defun shr-copy-url ()
93   "Copy the URL under point to the kill ring.
94 If called twice, then try to fetch the URL and see whether it
95 redirects somewhere else."
96   (interactive)
97   (let ((url (get-text-property (point) 'shr-url)))
98     (cond
99      ((not url)
100       (message "No URL under point"))
101      ;; Resolve redirected URLs.
102      ((equal url (car kill-ring))
103       (url-retrieve
104        url
105        (lambda (a)
106          (when (and (consp a)
107                     (eq (car a) :redirect))
108            (with-temp-buffer
109              (insert (cadr a))
110              (goto-char (point-min))
111              ;; Remove common tracking junk from the URL.
112              (when (re-search-forward ".utm_.*" nil t)
113                (replace-match "" t t))
114              (message "Copied %s" (buffer-string))
115              (copy-region-as-kill (point-min) (point-max)))))))
116      ;; Copy the URL to the kill ring.
117      (t
118       (with-temp-buffer
119         (insert url)
120         (copy-region-as-kill (point-min) (point-max))
121         (message "Copied %s" url))))))
122
123 (defun shr-show-alt-text ()
124   "Show the ALT text of the image under point."
125   (interactive)
126   (let ((text (get-text-property (point) 'shr-alt)))
127     (if (not text)
128         (message "No image under point")
129       (message "%s" text))))
130
131 (defun shr-browse-image ()
132   "Browse the image under point."
133   (interactive)
134   (let ((url (get-text-property (point) 'shr-image)))
135     (if (not url)
136         (message "No image under point")
137       (message "Browsing %s..." url)
138       (browse-url url))))
139
140 (defun shr-insert-image ()
141   "Insert the image under point into the buffer."
142   (interactive)
143   (let ((url (get-text-property (point) 'shr-image)))
144     (if (not url)
145         (message "No image under point")
146       (message "Inserting %s..." url)
147       (url-retrieve url 'shr-image-fetched
148                     (list (current-buffer) (1- (point)) (point-marker))
149                     t))))
150
151 ;;; Utility functions.
152
153 (defun shr-transform-dom (dom)
154   (let ((result (list (pop dom))))
155     (dolist (arg (pop dom))
156       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
157                   (cdr arg))
158             result))
159     (dolist (sub dom)
160       (if (stringp sub)
161           (push (cons :text sub) result)
162         (push (shr-transform-dom sub) result)))
163     (nreverse result)))
164
165 (defun shr-descend (dom)
166   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
167     (if (fboundp function)
168         (funcall function (cdr dom))
169       (shr-generic (cdr dom)))))
170
171 (defun shr-generic (cont)
172   (dolist (sub cont)
173     (cond
174      ((eq (car sub) :text)
175       (shr-insert (cdr sub)))
176      ((listp (cdr sub))
177       (shr-descend sub)))))
178
179 (defun shr-insert (text)
180   (when (eq shr-state 'image)
181     (insert "\n")
182     (setq shr-state nil))
183   (cond
184    ((eq shr-folding-mode 'none)
185     (insert text))
186    (t
187     (let ((first t)
188           column)
189       (when (and (string-match "\\`[ \t\n]" text)
190                  (not (bolp)))
191         (insert " "))
192       (dolist (elem (split-string text))
193         (when (and (bolp)
194                    (> shr-indentation 0))
195           (shr-indent))
196         ;; The shr-start is a special variable that is used to pass
197         ;; upwards the first point in the buffer where the text really
198         ;; starts.
199         (unless shr-start
200           (setq shr-start (point)))
201         (insert elem)
202         (when (> (current-column) shr-width)
203           (if (not (search-backward " " (line-beginning-position) t))
204               (insert "\n")
205             (delete-char 1)
206             (insert "\n")
207             (put-text-property (1- (point)) (point) 'shr-break t)
208             (when (> shr-indentation 0)
209               (shr-indent))
210             (end-of-line)))
211         (insert " "))
212       (unless (string-match "[ \t\n]\\'" text)
213         (delete-char -1))))))
214
215 (defun shr-ensure-newline ()
216   (unless (zerop (current-column))
217     (insert "\n")))
218
219 (defun shr-ensure-paragraph ()
220   (unless (bobp)
221     (if (bolp)
222         (unless (save-excursion
223                   (forward-line -1)
224                   (looking-at " *$"))
225           (insert "\n"))
226       (if (save-excursion
227             (beginning-of-line)
228             (looking-at " *$"))
229           (insert "\n")
230         (insert "\n\n")))))
231
232 (defun shr-indent ()
233   (insert (make-string shr-indentation ? )))
234
235 (defun shr-fontize-cont (cont &rest types)
236   (let (shr-start)
237     (shr-generic cont)
238     (dolist (type types)
239       (shr-add-font (or shr-start (point)) (point) type))))
240
241 (defun shr-add-font (start end type)
242   (let ((overlay (make-overlay start end)))
243     (overlay-put overlay 'face type)))
244
245 (defun shr-browse-url ()
246   "Browse the URL under point."
247   (interactive)
248   (let ((url (get-text-property (point) 'shr-url)))
249     (if (not url)
250         (message "No link under point")
251       (browse-url url))))
252
253 (defun shr-image-fetched (status buffer start end)
254   (when (and (buffer-name buffer)
255              (not (plist-get status :error)))
256     (url-store-in-cache (current-buffer))
257     (when (or (search-forward "\n\n" nil t)
258               (search-forward "\r\n\r\n" nil t))
259       (let ((data (buffer-substring (point) (point-max))))
260         (with-current-buffer buffer
261           (let ((alt (buffer-substring start end))
262                 (inhibit-read-only t))
263             (delete-region start end)
264             (shr-put-image data start alt))))))
265   (kill-buffer (current-buffer)))
266
267 (defun shr-put-image (data point alt)
268   (if (not (display-graphic-p))
269       (insert alt)
270     (let ((image (ignore-errors
271                    (shr-rescale-image data))))
272       (when image
273         (put-image image point alt)))))
274
275 (defun shr-rescale-image (data)
276   (if (or (not (fboundp 'imagemagick-types))
277           (not (get-buffer-window (current-buffer))))
278       (create-image data nil t)
279     (let* ((image (create-image data nil t))
280            (size (image-size image t))
281            (width (car size))
282            (height (cdr size))
283            (edges (window-inside-pixel-edges
284                    (get-buffer-window (current-buffer))))
285            (window-width (truncate (* shr-max-image-proportion
286                                       (- (nth 2 edges) (nth 0 edges)))))
287            (window-height (truncate (* shr-max-image-proportion
288                                        (- (nth 3 edges) (nth 1 edges)))))
289            scaled-image)
290       (when (> height window-height)
291         (setq image (or (create-image data 'imagemagick t
292                                       :height window-height)
293                         image))
294         (setq size (image-size image t)))
295       (when (> (car size) window-width)
296         (setq image (or
297                      (create-image data 'imagemagick t
298                                    :width window-width)
299                      image)))
300       image)))
301
302 (defun shr-get-image-data (url)
303   "Get image data for URL.
304 Return a string with image data."
305   (with-temp-buffer
306     (mm-disable-multibyte)
307     (when (ignore-errors
308             (url-cache-extract (url-cache-create-filename url))
309             t)
310       (when (or (search-forward "\n\n" nil t)
311                 (search-forward "\r\n\r\n" nil t))
312         (buffer-substring (point) (point-max))))))
313
314 (defun shr-heading (cont &rest types)
315   (shr-ensure-paragraph)
316   (apply #'shr-fontize-cont cont types)
317   (shr-ensure-paragraph))
318
319 ;;; Tag-specific rendering rules.
320
321 (defun shr-tag-p (cont)
322   (shr-ensure-paragraph)
323   (shr-generic cont)
324   (shr-ensure-paragraph))
325
326 (defun shr-tag-b (cont)
327   (shr-fontize-cont cont 'bold))
328
329 (defun shr-tag-i (cont)
330   (shr-fontize-cont cont 'italic))
331
332 (defun shr-tag-em (cont)
333   (shr-fontize-cont cont 'bold))
334
335 (defun shr-tag-u (cont)
336   (shr-fontize-cont cont 'underline))
337
338 (defun shr-tag-s (cont)
339   (shr-fontize-cont cont 'strike-through))
340
341 (defun shr-tag-a (cont)
342   (let ((url (cdr (assq :href cont)))
343         (start (point))
344         shr-start)
345     (shr-generic cont)
346     (widget-convert-button
347      'link (or shr-start start) (point)
348      :help-echo url)
349     (put-text-property (or shr-start start) (point) 'keymap shr-map)
350     (put-text-property (or shr-start start) (point) 'shr-url url)))
351
352 (defun shr-tag-img (cont)
353   (when (and (> (current-column) 0)
354              (not (eq shr-state 'image)))
355     (insert "\n"))
356   (let ((start (point-marker)))
357     (let ((alt (cdr (assq :alt cont)))
358           (url (cdr (assq :src cont))))
359       (when (zerop (length alt))
360         (setq alt "[img]"))
361       (cond
362        ((and (not shr-inhibit-images)
363              (string-match "\\`cid:" url))
364         (let ((url (substring url (match-end 0)))
365               image)
366           (if (or (not shr-content-function)
367                   (not (setq image (funcall shr-content-function url))))
368               (insert alt)
369             (shr-put-image image (point) alt))))
370        ((or shr-inhibit-images
371             (and shr-blocked-images
372                  (string-match shr-blocked-images url)))
373         (setq shr-start (point))
374         (let ((shr-state 'space))
375           (if (> (length alt) 8)
376               (shr-insert (substring alt 0 8))
377             (shr-insert alt))))
378        ((url-is-cached (browse-url-url-encode-chars url "[&)$ ]"))
379         (shr-put-image (shr-get-image-data url) (point) alt))
380        (t
381         (insert alt)
382         (ignore-errors
383           (url-retrieve url 'shr-image-fetched
384                         (list (current-buffer) start (point-marker))
385                         t))))
386       (insert " ")
387       (put-text-property start (point) 'keymap shr-map)
388       (put-text-property start (point) 'shr-alt alt)
389       (put-text-property start (point) 'shr-image url)
390       (setq shr-state 'image))))
391
392 (defun shr-tag-pre (cont)
393   (let ((shr-folding-mode 'none))
394     (shr-ensure-newline)
395     (shr-generic cont)
396     (shr-ensure-newline)))
397
398 (defun shr-tag-blockquote (cont)
399   (shr-ensure-paragraph)
400   (let ((shr-indentation (+ shr-indentation 4)))
401     (shr-generic cont))
402   (shr-ensure-paragraph))
403
404 (defun shr-tag-ul (cont)
405   (shr-ensure-paragraph)
406   (let ((shr-list-mode 'ul))
407     (shr-generic cont)))
408
409 (defun shr-tag-ol (cont)
410   (let ((shr-list-mode 1))
411     (shr-generic cont)))
412
413 (defun shr-tag-li (cont)
414   (shr-ensure-newline)
415   (let* ((bullet
416           (if (numberp shr-list-mode)
417               (prog1
418                   (format "%d " shr-list-mode)
419                 (setq shr-list-mode (1+ shr-list-mode)))
420             "* "))
421          (shr-indentation (+ shr-indentation (length bullet))))
422     (insert bullet)
423     (shr-generic cont)))
424
425 (defun shr-tag-br (cont)
426   (unless (bobp)
427     (insert "\n"))
428   (shr-generic cont))
429
430 (defun shr-tag-h1 (cont)
431   (shr-heading cont 'bold 'underline))
432
433 (defun shr-tag-h2 (cont)
434   (shr-heading cont 'bold))
435
436 (defun shr-tag-h3 (cont)
437   (shr-heading cont 'italic))
438
439 (defun shr-tag-h4 (cont)
440   (shr-heading cont))
441
442 (defun shr-tag-h5 (cont)
443   (shr-heading cont))
444
445 (defun shr-tag-h6 (cont)
446   (shr-heading cont))
447
448 ;;; Table rendering algorithm.
449
450 ;; Table rendering is the only complicated thing here.  We do this by
451 ;; first counting how many TDs there are in each TR, and registering
452 ;; how wide they think they should be ("width=45%", etc).  Then we
453 ;; render each TD separately (this is done in temporary buffers, so
454 ;; that we can use all the rendering machinery as if we were in the
455 ;; main buffer).  Now we know how much space each TD really takes, so
456 ;; we then render everything again with the new widths, and finally
457 ;; insert all these boxes into the main buffer.
458 (defun shr-tag-table (cont)
459   (shr-ensure-paragraph)
460   (setq cont (or (cdr (assq 'tbody cont))
461                  cont))
462   (let* ((shr-inhibit-images t)
463          ;; Find all suggested widths.
464          (columns (shr-column-specs cont))
465          ;; Compute how many characters wide each TD should be.
466          (suggested-widths (shr-pro-rate-columns columns))
467          ;; Do a "test rendering" to see how big each TD is (this can
468          ;; be smaller (if there's little text) or bigger (if there's
469          ;; unbreakable text).
470          (sketch (shr-make-table cont suggested-widths))
471          (sketch-widths (shr-table-widths sketch suggested-widths)))
472     ;; Then render the table again with these new "hard" widths.
473     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
474   ;; Finally, insert all the images after the table.  The Emacs buffer
475   ;; model isn't strong enough to allow us to put the images actually
476   ;; into the tables.
477   (dolist (elem (shr-find-elements cont 'img))
478     (shr-tag-img (cdr elem))))
479
480 (defun shr-find-elements (cont type)
481   (let (result)
482     (dolist (elem cont)
483       (cond ((eq (car elem) type)
484              (push elem result))
485             ((consp (cdr elem))
486              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
487     (nreverse result)))
488
489 (defun shr-insert-table (table widths)
490   (shr-insert-table-ruler widths)
491   (dolist (row table)
492     (let ((start (point))
493           (height (let ((max 0))
494                     (dolist (column row)
495                       (setq max (max max (cadr column))))
496                     max)))
497       (dotimes (i height)
498         (shr-indent)
499         (insert "|\n"))
500       (dolist (column row)
501         (goto-char start)
502         (let ((lines (nth 2 column))
503               (overlay-lines (nth 3 column))
504               overlay overlay-line)
505           (dolist (line lines)
506             (setq overlay-line (pop overlay-lines))
507             (when (> (length line) 0)
508               (end-of-line)
509               (insert line "|")
510               (dolist (overlay overlay-line)
511                 (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
512                                        (- (point) (nth 1 overlay) 1)))
513                       (properties (nth 2 overlay)))
514                   (while properties
515                     (overlay-put o (pop properties) (pop properties)))))
516               (forward-line 1)))
517           ;; Add blank lines at padding at the bottom of the TD,
518           ;; possibly.
519           (dotimes (i (- height (length lines)))
520             (end-of-line)
521             (insert (make-string (length (car lines)) ? ) "|")
522             (forward-line 1)))))
523     (shr-insert-table-ruler widths)))
524
525 (defun shr-insert-table-ruler (widths)
526   (shr-indent)
527   (insert "+")
528   (dotimes (i (length widths))
529     (insert (make-string (aref widths i) ?-) ?+))
530   (insert "\n"))
531
532 (defun shr-table-widths (table suggested-widths)
533   (let* ((length (length suggested-widths))
534          (widths (make-vector length 0))
535          (natural-widths (make-vector length 0)))
536     (dolist (row table)
537       (let ((i 0))
538         (dolist (column row)
539           (aset widths i (max (aref widths i)
540                               (car column)))
541           (aset natural-widths i (max (aref natural-widths i)
542                                       (cadr column)))
543           (setq i (1+ i)))))
544     (let ((extra (- (reduce '+ suggested-widths)
545                     (reduce '+ widths)))
546           (expanded-columns 0))
547       (when (> extra 0)
548         (dotimes (i length)
549           ;; If the natural width is wider than the rendered width, we
550           ;; want to allow the column to expand.
551           (when (> (aref natural-widths i) (aref widths i))
552             (setq expanded-columns (1+ expanded-columns))))
553         (dotimes (i length)
554           (when (> (aref natural-widths i) (aref widths i))
555             (aset widths i (min
556                             (1+ (aref natural-widths i))
557                             (+ (/ extra expanded-columns)
558                                (aref widths i))))))))
559     widths))
560
561 (defun shr-make-table (cont widths &optional fill)
562   (let ((trs nil))
563     (dolist (row cont)
564       (when (eq (car row) 'tr)
565         (let ((tds nil)
566               (columns (cdr row))
567               (i 0)
568               column)
569           (while (< i (length widths))
570             (setq column (pop columns))
571             (when (or (memq (car column) '(td th))
572                       (null column))
573               (push (shr-render-td (cdr column) (aref widths i) fill)
574                     tds)
575               (setq i (1+ i))))
576           (push (nreverse tds) trs))))
577     (nreverse trs)))
578
579 (defun shr-render-td (cont width fill)
580   (with-temp-buffer
581     (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
582       (if cache
583           (insert cache)
584         (let ((shr-width width)
585               (shr-indentation 0))
586           (shr-generic cont))
587         (delete-region
588          (point)
589          (+ (point)
590             (skip-chars-backward " \t\n")))
591         (push (cons (cons width cont) (buffer-string))
592               shr-content-cache)))
593     (goto-char (point-min))
594     (let ((max 0))
595       (while (not (eobp))
596         (end-of-line)
597         (setq max (max max (current-column)))
598         (forward-line 1))
599       (when fill
600         (goto-char (point-min))
601         ;; If the buffer is totally empty, then put a single blank
602         ;; line here.
603         (if (zerop (buffer-size))
604             (insert (make-string width ? ))
605           ;; Otherwise, fill the buffer.
606           (while (not (eobp))
607             (end-of-line)
608             (when (> (- width (current-column)) 0)
609               (insert (make-string (- width (current-column)) ? )))
610             (forward-line 1))))
611       (if fill
612           (list max
613                 (count-lines (point-min) (point-max))
614                 (split-string (buffer-string) "\n")
615                 (shr-collect-overlays))
616         (list max
617               (shr-natural-width))))))
618
619 (defun shr-natural-width ()
620   (goto-char (point-min))
621   (let ((current 0)
622         (max 0))
623     (while (not (eobp))
624       (end-of-line)
625       (setq current (+ current (current-column)))
626       (unless (get-text-property (point) 'shr-break)
627         (setq max (max max current)
628               current 0))
629       (forward-line 1))
630     max))
631
632 (defun shr-collect-overlays ()
633   (save-excursion
634     (goto-char (point-min))
635     (let ((overlays nil))
636       (while (not (eobp))
637         (push (shr-overlays-in-region (point) (line-end-position))
638               overlays)
639         (forward-line 1))
640       (nreverse overlays))))
641
642 (defun shr-overlays-in-region (start end)
643   (let (result)
644     (dolist (overlay (overlays-in start end))
645       (push (list (if (> start (overlay-start overlay))
646                       (- end start)
647                     (- end (overlay-start overlay)))
648                   (if (< end (overlay-end overlay))
649                       0
650                     (- end (overlay-end overlay)))
651                   (overlay-properties overlay))
652             result))
653     (nreverse result)))
654
655 (defun shr-pro-rate-columns (columns)
656   (let ((total-percentage 0)
657         (widths (make-vector (length columns) 0)))
658     (dotimes (i (length columns))
659       (setq total-percentage (+ total-percentage (aref columns i))))
660     (setq total-percentage (/ 1.0 total-percentage))
661     (dotimes (i (length columns))
662       (aset widths i (max (truncate (* (aref columns i)
663                                        total-percentage
664                                        (- shr-width (1+ (length columns)))))
665                           10)))
666     widths))
667
668 ;; Return a summary of the number and shape of the TDs in the table.
669 (defun shr-column-specs (cont)
670   (let ((columns (make-vector (shr-max-columns cont) 1)))
671     (dolist (row cont)
672       (when (eq (car row) 'tr)
673         (let ((i 0))
674           (dolist (column (cdr row))
675             (when (memq (car column) '(td th))
676               (let ((width (cdr (assq :width (cdr column)))))
677                 (when (and width
678                            (string-match "\\([0-9]+\\)%" width))
679                   (aset columns i
680                         (/ (string-to-number (match-string 1 width))
681                            100.0))))
682               (setq i (1+ i)))))))
683     columns))
684
685 (defun shr-count (cont elem)
686   (let ((i 0))
687     (dolist (sub cont)
688       (when (eq (car sub) elem)
689         (setq i (1+ i))))
690     i))
691
692 (defun shr-max-columns (cont)
693   (let ((max 0))
694     (dolist (row cont)
695       (when (eq (car row) 'tr)
696         (setq max (max max (+ (shr-count (cdr row) 'td)
697                               (shr-count (cdr row) 'th))))))
698     max))
699
700 (provide 'shr)
701
702 ;;; shr.el ends here