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