(shr-tag-img): Ignore very small web bug type images.
[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 (unless (aref (char-category-set (make-char 'japanese-jisx0208 33 35)) ?>)
36   (load "kinsoku" nil t))
37
38 (defgroup shr nil
39   "Simple HTML Renderer"
40   :group 'mail)
41
42 (defcustom shr-max-image-proportion 0.9
43   "How big pictures displayed are in relation to the window they're in.
44 A value of 0.7 means that they are allowed to take up 70% of the
45 width and height of the window.  If they are larger than this,
46 and Emacs supports it, then the images will be rescaled down to
47 fit these criteria."
48   :version "24.1"
49   :group 'shr
50   :type 'float)
51
52 (defcustom shr-blocked-images nil
53   "Images that have URLs matching this regexp will be blocked."
54   :version "24.1"
55   :group 'shr
56   :type 'regexp)
57
58 (defcustom shr-table-line ?-
59   "Character used to draw table line."
60   :group 'shr
61   :type 'character)
62
63 (defcustom shr-table-corner ?+
64   "Character used to draw table corner."
65   :group 'shr
66   :type 'character)
67
68 (defcustom shr-hr-line ?-
69   "Character used to draw hr line."
70   :group 'shr
71   :type 'character)
72
73 (defcustom shr-width fill-column
74   "Frame width to use for rendering."
75   :type 'integer
76   :group 'shr)
77
78 (defvar shr-content-function nil
79   "If bound, this should be a function that will return the content.
80 This is used for cid: URLs, and the function is called with the
81 cid: URL as the argument.")
82
83 ;;; Internal variables.
84
85 (defvar shr-folding-mode nil)
86 (defvar shr-state nil)
87 (defvar shr-start nil)
88 (defvar shr-indentation 0)
89 (defvar shr-inhibit-images nil)
90 (defvar shr-list-mode nil)
91 (defvar shr-content-cache nil)
92 (defvar shr-kinsoku-shorten nil)
93 (defvar shr-table-depth 0)
94
95 (defvar shr-map
96   (let ((map (make-sparse-keymap)))
97     (define-key map "a" 'shr-show-alt-text)
98     (define-key map "i" 'shr-browse-image)
99     (define-key map "I" 'shr-insert-image)
100     (define-key map "u" 'shr-copy-url)
101     (define-key map "v" 'shr-browse-url)
102     (define-key map "o" 'shr-save-contents)
103     (define-key map "\r" 'shr-browse-url)
104     map))
105
106 ;; Public functions and commands.
107
108 ;;;###autoload
109 (defun shr-insert-document (dom)
110   (setq shr-content-cache nil)
111   (let ((shr-state nil)
112         (shr-start nil))
113     (shr-descend (shr-transform-dom dom))))
114
115 (defun shr-copy-url ()
116   "Copy the URL under point to the kill ring.
117 If called twice, then try to fetch the URL and see whether it
118 redirects somewhere else."
119   (interactive)
120   (let ((url (get-text-property (point) 'shr-url)))
121     (cond
122      ((not url)
123       (message "No URL under point"))
124      ;; Resolve redirected URLs.
125      ((equal url (car kill-ring))
126       (url-retrieve
127        url
128        (lambda (a)
129          (when (and (consp a)
130                     (eq (car a) :redirect))
131            (with-temp-buffer
132              (insert (cadr a))
133              (goto-char (point-min))
134              ;; Remove common tracking junk from the URL.
135              (when (re-search-forward ".utm_.*" nil t)
136                (replace-match "" t t))
137              (message "Copied %s" (buffer-string))
138              (copy-region-as-kill (point-min) (point-max)))))))
139      ;; Copy the URL to the kill ring.
140      (t
141       (with-temp-buffer
142         (insert url)
143         (copy-region-as-kill (point-min) (point-max))
144         (message "Copied %s" url))))))
145
146 (defun shr-show-alt-text ()
147   "Show the ALT text of the image under point."
148   (interactive)
149   (let ((text (get-text-property (point) 'shr-alt)))
150     (if (not text)
151         (message "No image under point")
152       (message "%s" text))))
153
154 (defun shr-browse-image ()
155   "Browse the image under point."
156   (interactive)
157   (let ((url (get-text-property (point) 'shr-image)))
158     (if (not url)
159         (message "No image under point")
160       (message "Browsing %s..." url)
161       (browse-url url))))
162
163 (defun shr-insert-image ()
164   "Insert the image under point into the buffer."
165   (interactive)
166   (let ((url (get-text-property (point) 'shr-image)))
167     (if (not url)
168         (message "No image under point")
169       (message "Inserting %s..." url)
170       (url-retrieve url 'shr-image-fetched
171                     (list (current-buffer) (1- (point)) (point-marker))
172                     t))))
173
174 ;;; Utility functions.
175
176 (defun shr-transform-dom (dom)
177   (let ((result (list (pop dom))))
178     (dolist (arg (pop dom))
179       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
180                   (cdr arg))
181             result))
182     (dolist (sub dom)
183       (if (stringp sub)
184           (push (cons :text sub) result)
185         (push (shr-transform-dom sub) result)))
186     (nreverse result)))
187
188 (defun shr-descend (dom)
189   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
190     (if (fboundp function)
191         (funcall function (cdr dom))
192       (shr-generic (cdr dom)))))
193
194 (defun shr-generic (cont)
195   (dolist (sub cont)
196     (cond
197      ((eq (car sub) :text)
198       (shr-insert (cdr sub)))
199      ((listp (cdr sub))
200       (shr-descend sub)))))
201
202 (defun shr-insert (text)
203   (when (and (eq shr-state 'image)
204              (not (string-match "\\`[ \t\n]+\\'" text)))
205     (insert "\n")
206     (setq shr-state nil))
207   (cond
208    ((eq shr-folding-mode 'none)
209     (insert text))
210    (t
211     (when (and (string-match "\\`[ \t\n]" text)
212                (not (bolp))
213                (not (eq (char-after (1- (point))) ? )))
214       (insert " "))
215     (dolist (elem (split-string text))
216       (when (and (bolp)
217                  (> shr-indentation 0))
218         (shr-indent))
219       ;; The shr-start is a special variable that is used to pass
220       ;; upwards the first point in the buffer where the text really
221       ;; starts.
222       (unless shr-start
223         (setq shr-start (point)))
224       ;; No space is needed behind a wide character categorized as
225       ;; kinsoku-bol, between characters both categorized as nospace,
226       ;; or at the beginning of a line.
227       (let (prev)
228         (when (and (eq (preceding-char) ? )
229                    (or (= (line-beginning-position) (1- (point)))
230                        (and (aref fill-find-break-point-function-table
231                                   (setq prev (char-after (- (point) 2))))
232                             (aref (char-category-set prev) ?>))
233                        (and (aref fill-nospace-between-words-table prev)
234                             (aref fill-nospace-between-words-table
235                                   (aref elem 0)))))
236           (delete-char -1)))
237       (insert elem)
238       (while (> (current-column) shr-width)
239         (unless (prog1
240                     (shr-find-fill-point)
241                   (when (eq (preceding-char) ? )
242                     (delete-char -1))
243                   (insert "\n"))
244           (put-text-property (1- (point)) (point) 'shr-break t)
245           ;; No space is needed at the beginning of a line.
246           (when (eq (following-char) ? )
247             (delete-char 1)))
248         (when (> shr-indentation 0)
249           (shr-indent))
250         (end-of-line))
251       (insert " "))
252     (unless (string-match "[ \t\n]\\'" text)
253       (delete-char -1)))))
254
255 (defun shr-find-fill-point ()
256   (when (> (move-to-column shr-width) shr-width)
257     (backward-char 1))
258   (let (failed)
259     (while (not
260             (or (setq failed (= (current-column) shr-indentation))
261                 (eq (preceding-char) ? )
262                 (eq (following-char) ? )
263                 (aref fill-find-break-point-function-table (preceding-char))))
264       (backward-char 1))
265     (if failed
266         ;; There's no breakable point, so we give it up.
267         (progn
268           (end-of-line)
269           (while (aref fill-find-break-point-function-table (preceding-char))
270             (backward-char 1))
271           nil)
272       (or (eolp)
273           ;; Don't put kinsoku-bol characters at the beginning of a line,
274           ;; or kinsoku-eol characters at the end of a line,
275           (let ((count 4))
276             (if (or shr-kinsoku-shorten
277                     (and (aref (char-category-set (preceding-char)) ?<)
278                          (progn
279                            (setq count (1- count))
280                            (backward-char 1)
281                            t)))
282                 (while (and
283                         (>= (setq count (1- count)) 0)
284                         (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
285                         (or (aref (char-category-set (preceding-char)) ?<)
286                             (aref (char-category-set (following-char)) ?>)))
287                   (backward-char 1))
288               (while (and (>= (setq count (1- count)) 0)
289                           (aref (char-category-set (following-char)) ?>))
290                 (forward-char 1)))
291             (when (eq (following-char) ? )
292               (forward-char 1))
293             t)))))
294
295 (defun shr-ensure-newline ()
296   (unless (zerop (current-column))
297     (insert "\n")))
298
299 (defun shr-ensure-paragraph ()
300   (unless (bobp)
301     (if (<= (current-column) shr-indentation)
302         (unless (save-excursion
303                   (forward-line -1)
304                   (looking-at " *$"))
305           (insert "\n"))
306       (if (save-excursion
307             (beginning-of-line)
308             (looking-at " *$"))
309           (insert "\n")
310         (insert "\n\n")))))
311
312 (defun shr-indent ()
313   (when (> shr-indentation 0)
314     (insert (make-string shr-indentation ? ))))
315
316 (defun shr-fontize-cont (cont &rest types)
317   (let (shr-start)
318     (shr-generic cont)
319     (dolist (type types)
320       (shr-add-font (or shr-start (point)) (point) type))))
321
322 ;; Add an overlay in the region, but avoid putting the font properties
323 ;; on blank text at the start of the line, and the newline at the end,
324 ;; to avoid ugliness.
325 (defun shr-add-font (start end type)
326   (save-excursion
327     (goto-char start)
328     (while (< (point) end)
329       (when (bolp)
330         (skip-chars-forward " "))
331       (let ((overlay (make-overlay (point) (min (line-end-position) end))))
332         (overlay-put overlay 'face type))
333       (if (< (line-end-position) end)
334           (forward-line 1)
335         (goto-char end)))))
336
337 (defun shr-browse-url ()
338   "Browse the URL under point."
339   (interactive)
340   (let ((url (get-text-property (point) 'shr-url)))
341     (if (not url)
342         (message "No link under point")
343       (browse-url url))))
344
345 (defun shr-save-contents (directory)
346   "Save the contents from URL in a file."
347   (interactive "DSave contents of URL to directory: ")
348   (let ((url (get-text-property (point) 'shr-url)))
349     (if (not url)
350         (message "No link under point")
351       (url-retrieve (shr-encode-url url)
352                     'shr-store-contents (list url directory)))))
353
354 (defun shr-store-contents (status url directory)
355   (unless (plist-get status :error)
356     (when (or (search-forward "\n\n" nil t)
357               (search-forward "\r\n\r\n" nil t))
358       (write-region (point) (point-max)
359                     (expand-file-name (file-name-nondirectory url)
360                                       directory)))))
361
362 (defun shr-image-fetched (status buffer start end)
363   (when (and (buffer-name buffer)
364              (not (plist-get status :error)))
365     (url-store-in-cache (current-buffer))
366     (when (or (search-forward "\n\n" nil t)
367               (search-forward "\r\n\r\n" nil t))
368       (let ((data (buffer-substring (point) (point-max))))
369         (with-current-buffer buffer
370           (let ((alt (buffer-substring start end))
371                 (inhibit-read-only t))
372             (delete-region start end)
373             (shr-put-image data start alt))))))
374   (kill-buffer (current-buffer)))
375
376 (defun shr-put-image (data point alt)
377   (if (display-graphic-p)
378       (let ((image (ignore-errors
379                      (shr-rescale-image data))))
380         (when image
381           (put-image image point alt)))
382     (save-excursion
383       (goto-char point)
384       (insert alt))))
385
386 (defun shr-rescale-image (data)
387   (if (or (not (fboundp 'imagemagick-types))
388           (not (get-buffer-window (current-buffer))))
389       (create-image data nil t)
390     (let* ((image (create-image data nil t))
391            (size (image-size image t))
392            (width (car size))
393            (height (cdr size))
394            (edges (window-inside-pixel-edges
395                    (get-buffer-window (current-buffer))))
396            (window-width (truncate (* shr-max-image-proportion
397                                       (- (nth 2 edges) (nth 0 edges)))))
398            (window-height (truncate (* shr-max-image-proportion
399                                        (- (nth 3 edges) (nth 1 edges)))))
400            scaled-image)
401       (when (> height window-height)
402         (setq image (or (create-image data 'imagemagick t
403                                       :height window-height)
404                         image))
405         (setq size (image-size image t)))
406       (when (> (car size) window-width)
407         (setq image (or
408                      (create-image data 'imagemagick t
409                                    :width window-width)
410                      image)))
411       image)))
412
413 (defun shr-get-image-data (url)
414   "Get image data for URL.
415 Return a string with image data."
416   (with-temp-buffer
417     (mm-disable-multibyte)
418     (when (ignore-errors
419             (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
420             t)
421       (when (or (search-forward "\n\n" nil t)
422                 (search-forward "\r\n\r\n" nil t))
423         (buffer-substring (point) (point-max))))))
424
425 (defun shr-heading (cont &rest types)
426   (shr-ensure-paragraph)
427   (apply #'shr-fontize-cont cont types)
428   (shr-ensure-paragraph))
429
430 (defun shr-urlify (start url)
431   (widget-convert-button
432    'url-link start (point)
433    :help-echo url
434    :keymap shr-map
435    url)
436   (put-text-property start (point) 'shr-url url))
437
438 (defun shr-encode-url (url)
439   "Encode URL."
440   (browse-url-url-encode-chars url "[)$ ]"))
441
442 ;;; Tag-specific rendering rules.
443
444 (defun shr-tag-p (cont)
445   (shr-ensure-paragraph)
446   (shr-indent)
447   (shr-generic cont)
448   (shr-ensure-paragraph))
449
450 (defun shr-tag-div (cont)
451   (shr-ensure-newline)
452   (shr-indent)
453   (shr-generic cont)
454   (shr-ensure-newline))
455
456 (defun shr-tag-b (cont)
457   (shr-fontize-cont cont 'bold))
458
459 (defun shr-tag-i (cont)
460   (shr-fontize-cont cont 'italic))
461
462 (defun shr-tag-em (cont)
463   (shr-fontize-cont cont 'bold))
464
465 (defun shr-tag-strong (cont)
466   (shr-fontize-cont cont 'bold))
467
468 (defun shr-tag-u (cont)
469   (shr-fontize-cont cont 'underline))
470
471 (defun shr-tag-s (cont)
472   (shr-fontize-cont cont 'strike-through))
473
474 (defun shr-parse-style (style)
475   (when style
476     (let ((plist nil))
477       (dolist (elem (split-string style ";"))
478         (when elem
479           (setq elem (split-string elem ":"))
480           (when (and (car elem)
481                      (cadr elem))
482             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
483                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
484               (push (cons (intern name obarray)
485                           value)
486                     plist)))))
487       plist)))
488
489 (defun shr-tag-a (cont)
490   (let ((url (cdr (assq :href cont)))
491         (start (point))
492         shr-start)
493     (shr-generic cont)
494     (shr-urlify (or shr-start start) url)))
495
496 (defun shr-tag-object (cont)
497   (let ((url (cdr (assq :src (cdr (assq 'embed cont)))))
498         (start (point)))
499     (when url
500       (shr-insert " [multimedia] ")
501       (shr-urlify start url))))
502
503 (defun shr-tag-img (cont)
504   (when (and cont
505              (cdr (assq :src cont)))
506     (when (and (> (current-column) 0)
507                (not (eq shr-state 'image)))
508       (insert "\n"))
509     (let ((alt (cdr (assq :alt cont)))
510           (url (cdr (assq :src cont))))
511       (let ((start (point-marker)))
512         (when (zerop (length alt))
513           (setq alt "[img]"))
514         (cond
515          ((or (member (cdr (assq :height cont)) '("0" "1"))
516               (member (cdr (assq :width cont)) '("0" "1")))
517           ;; Ignore zero-sized or single-pixel images.
518           )
519          ((and (not shr-inhibit-images)
520                (string-match "\\`cid:" url))
521           (let ((url (substring url (match-end 0)))
522                 image)
523             (if (or (not shr-content-function)
524                     (not (setq image (funcall shr-content-function url))))
525                 (insert alt)
526               (shr-put-image image (point) alt))))
527          ((or shr-inhibit-images
528               (and shr-blocked-images
529                    (string-match shr-blocked-images url)))
530           (setq shr-start (point))
531           (let ((shr-state 'space))
532             (if (> (length alt) 8)
533                 (shr-insert (substring alt 0 8))
534               (shr-insert alt))))
535          ((url-is-cached (shr-encode-url url))
536           (shr-put-image (shr-get-image-data url) (point) alt))
537          (t
538           (insert alt)
539           (ignore-errors
540             (url-retrieve (shr-encode-url url) 'shr-image-fetched
541                           (list (current-buffer) start (point-marker))
542                           t))))
543         (insert " ")
544         (put-text-property start (point) 'keymap shr-map)
545         (put-text-property start (point) 'shr-alt alt)
546         (put-text-property start (point) 'shr-image url)
547         (setq shr-state 'image)))))
548
549 (defun shr-tag-pre (cont)
550   (let ((shr-folding-mode 'none))
551     (shr-ensure-newline)
552     (shr-indent)
553     (shr-generic cont)
554     (shr-ensure-newline)))
555
556 (defun shr-tag-blockquote (cont)
557   (shr-ensure-paragraph)
558   (shr-indent)
559   (let ((shr-indentation (+ shr-indentation 4)))
560     (shr-generic cont))
561   (shr-ensure-paragraph))
562
563 (defun shr-tag-ul (cont)
564   (shr-ensure-paragraph)
565   (let ((shr-list-mode 'ul))
566     (shr-generic cont))
567   (shr-ensure-paragraph))
568
569 (defun shr-tag-ol (cont)
570   (shr-ensure-paragraph)
571   (let ((shr-list-mode 1))
572     (shr-generic cont))
573   (shr-ensure-paragraph))
574
575 (defun shr-tag-li (cont)
576   (shr-ensure-paragraph)
577   (shr-indent)
578   (let* ((bullet
579           (if (numberp shr-list-mode)
580               (prog1
581                   (format "%d " shr-list-mode)
582                 (setq shr-list-mode (1+ shr-list-mode)))
583             "* "))
584          (shr-indentation (+ shr-indentation (length bullet))))
585     (insert bullet)
586     (shr-generic cont)))
587
588 (defun shr-tag-br (cont)
589   (unless (bobp)
590     (insert "\n")
591     (shr-indent))
592   (shr-generic cont))
593
594 (defun shr-tag-h1 (cont)
595   (shr-heading cont 'bold 'underline))
596
597 (defun shr-tag-h2 (cont)
598   (shr-heading cont 'bold))
599
600 (defun shr-tag-h3 (cont)
601   (shr-heading cont 'italic))
602
603 (defun shr-tag-h4 (cont)
604   (shr-heading cont))
605
606 (defun shr-tag-h5 (cont)
607   (shr-heading cont))
608
609 (defun shr-tag-h6 (cont)
610   (shr-heading cont))
611
612 (defun shr-tag-hr (cont)
613   (shr-ensure-newline)
614   (insert (make-string shr-width shr-hr-line) "\n"))
615
616 ;;; Table rendering algorithm.
617
618 ;; Table rendering is the only complicated thing here.  We do this by
619 ;; first counting how many TDs there are in each TR, and registering
620 ;; how wide they think they should be ("width=45%", etc).  Then we
621 ;; render each TD separately (this is done in temporary buffers, so
622 ;; that we can use all the rendering machinery as if we were in the
623 ;; main buffer).  Now we know how much space each TD really takes, so
624 ;; we then render everything again with the new widths, and finally
625 ;; insert all these boxes into the main buffer.
626 (defun shr-tag-table-1 (cont)
627   (setq cont (or (cdr (assq 'tbody cont))
628                  cont))
629   (let* ((shr-inhibit-images t)
630          (shr-table-depth (1+ shr-table-depth))
631          (shr-kinsoku-shorten t)
632          ;; Find all suggested widths.
633          (columns (shr-column-specs cont))
634          ;; Compute how many characters wide each TD should be.
635          (suggested-widths (shr-pro-rate-columns columns))
636          ;; Do a "test rendering" to see how big each TD is (this can
637          ;; be smaller (if there's little text) or bigger (if there's
638          ;; unbreakable text).
639          (sketch (shr-make-table cont suggested-widths))
640          (sketch-widths (shr-table-widths sketch suggested-widths)))
641     ;; This probably won't work very well.
642     (when (> (+ (loop for width across sketch-widths
643                       summing (1+ width))
644                 shr-indentation 1)
645              (frame-width))
646       (setq truncate-lines t))
647     ;; Then render the table again with these new "hard" widths.
648     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
649   ;; Finally, insert all the images after the table.  The Emacs buffer
650   ;; model isn't strong enough to allow us to put the images actually
651   ;; into the tables.
652   (when (zerop shr-table-depth)
653     (dolist (elem (shr-find-elements cont 'img))
654       (shr-tag-img (cdr elem)))))
655
656 (defun shr-tag-table (cont)
657   (shr-ensure-paragraph)
658   (let* ((caption (cdr (assq 'caption cont)))
659          (header (cdr (assq 'thead cont)))
660          (body (or (cdr (assq 'tbody cont)) cont))
661          (footer (cdr (assq 'tfoot cont)))
662          (nheader (if header (shr-max-columns header)))
663          (nbody (if body (shr-max-columns body)))
664          (nfooter (if footer (shr-max-columns footer))))
665     (shr-tag-table-1
666      (nconc
667       (if caption `((tr (td ,@caption))))
668       (if header
669           (if footer
670               ;; hader + body + footer
671               (if (= nheader nbody)
672                   (if (= nbody nfooter)
673                       `((tr (td (table (tbody ,@header ,@body ,@footer)))))
674                     (nconc `((tr (td (table (tbody ,@header ,@body)))))
675                            (if (= nfooter 1)
676                                footer
677                              `((tr (td (table (tbody ,@footer))))))))
678                 (nconc `((tr (td (table (tbody ,@header)))))
679                        (if (= nbody nfooter)
680                            `((tr (td (table (tbody ,@body ,@footer)))))
681                          (nconc `((tr (td (table (tbody ,@body)))))
682                                 (if (= nfooter 1)
683                                     footer
684                                   `((tr (td (table (tbody ,@footer))))))))))
685             ;; header + body
686             (if (= nheader nbody)
687                 `((tr (td (table (tbody ,@header ,@body)))))
688               (if (= nheader 1)
689                   `(,@header (tr (td (table (tbody ,@body)))))
690                 `((tr (td (table (tbody ,@header))))
691                   (tr (td (table (tbody ,@body))))))))
692         (if footer
693             ;; body + footer
694             (if (= nbody nfooter)
695                 `((tr (td (table (tbody ,@body ,@footer)))))
696               (nconc `((tr (td (table (tbody ,@body)))))
697                      (if (= nfooter 1)
698                          footer
699                        `((tr (td (table (tbody ,@footer))))))))
700           (if caption
701               `((tr (td (table (tbody ,@body)))))
702             body)))))))
703
704 (defun shr-find-elements (cont type)
705   (let (result)
706     (dolist (elem cont)
707       (cond ((eq (car elem) type)
708              (push elem result))
709             ((consp (cdr elem))
710              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
711     (nreverse result)))
712
713 (defun shr-insert-table (table widths)
714   (shr-insert-table-ruler widths)
715   (dolist (row table)
716     (let ((start (point))
717           (height (let ((max 0))
718                     (dolist (column row)
719                       (setq max (max max (cadr column))))
720                     max)))
721       (dotimes (i height)
722         (shr-indent)
723         (insert "|\n"))
724       (dolist (column row)
725         (goto-char start)
726         (let ((lines (nth 2 column))
727               (overlay-lines (nth 3 column))
728               overlay overlay-line)
729           (dolist (line lines)
730             (setq overlay-line (pop overlay-lines))
731             (end-of-line)
732             (insert line "|")
733             (dolist (overlay overlay-line)
734               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
735                                      (- (point) (nth 1 overlay) 1)))
736                     (properties (nth 2 overlay)))
737                 (while properties
738                   (overlay-put o (pop properties) (pop properties)))))
739             (forward-line 1))
740           ;; Add blank lines at padding at the bottom of the TD,
741           ;; possibly.
742           (dotimes (i (- height (length lines)))
743             (end-of-line)
744             (insert (make-string (string-width (car lines)) ? ) "|")
745             (forward-line 1)))))
746     (shr-insert-table-ruler widths)))
747
748 (defun shr-insert-table-ruler (widths)
749   (when (and (bolp)
750              (> shr-indentation 0))
751     (shr-indent))
752   (insert shr-table-corner)
753   (dotimes (i (length widths))
754     (insert (make-string (aref widths i) shr-table-line) shr-table-corner))
755   (insert "\n"))
756
757 (defun shr-table-widths (table suggested-widths)
758   (let* ((length (length suggested-widths))
759          (widths (make-vector length 0))
760          (natural-widths (make-vector length 0)))
761     (dolist (row table)
762       (let ((i 0))
763         (dolist (column row)
764           (aset widths i (max (aref widths i)
765                               (car column)))
766           (aset natural-widths i (max (aref natural-widths i)
767                                       (cadr column)))
768           (setq i (1+ i)))))
769     (let ((extra (- (apply '+ (append suggested-widths nil))
770                     (apply '+ (append widths nil))))
771           (expanded-columns 0))
772       (when (> extra 0)
773         (dotimes (i length)
774           ;; If the natural width is wider than the rendered width, we
775           ;; want to allow the column to expand.
776           (when (> (aref natural-widths i) (aref widths i))
777             (setq expanded-columns (1+ expanded-columns))))
778         (dotimes (i length)
779           (when (> (aref natural-widths i) (aref widths i))
780             (aset widths i (min
781                             (1+ (aref natural-widths i))
782                             (+ (/ extra expanded-columns)
783                                (aref widths i))))))))
784     widths))
785
786 (defun shr-make-table (cont widths &optional fill)
787   (let ((trs nil))
788     (dolist (row cont)
789       (when (eq (car row) 'tr)
790         (let ((tds nil)
791               (columns (cdr row))
792               (i 0)
793               column)
794           (while (< i (length widths))
795             (setq column (pop columns))
796             (when (or (memq (car column) '(td th))
797                       (null column))
798               (push (shr-render-td (cdr column) (aref widths i) fill)
799                     tds)
800               (setq i (1+ i))))
801           (push (nreverse tds) trs))))
802     (nreverse trs)))
803
804 (defun shr-render-td (cont width fill)
805   (with-temp-buffer
806     (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
807       (if cache
808           (insert cache)
809         (let ((shr-width width)
810               (shr-indentation 0))
811           (shr-generic cont))
812         (delete-region
813          (point)
814          (+ (point)
815             (skip-chars-backward " \t\n")))
816         (push (cons (cons width cont) (buffer-string))
817               shr-content-cache)))
818     (goto-char (point-min))
819     (let ((max 0))
820       (while (not (eobp))
821         (end-of-line)
822         (setq max (max max (current-column)))
823         (forward-line 1))
824       (when fill
825         (goto-char (point-min))
826         ;; If the buffer is totally empty, then put a single blank
827         ;; line here.
828         (if (zerop (buffer-size))
829             (insert (make-string width ? ))
830           ;; Otherwise, fill the buffer.
831           (while (not (eobp))
832             (end-of-line)
833             (when (> (- width (current-column)) 0)
834               (insert (make-string (- width (current-column)) ? )))
835             (forward-line 1))))
836       (if fill
837           (list max
838                 (count-lines (point-min) (point-max))
839                 (split-string (buffer-string) "\n")
840                 (shr-collect-overlays))
841         (list max
842               (shr-natural-width))))))
843
844 (defun shr-natural-width ()
845   (goto-char (point-min))
846   (let ((current 0)
847         (max 0))
848     (while (not (eobp))
849       (end-of-line)
850       (setq current (+ current (current-column)))
851       (unless (get-text-property (point) 'shr-break)
852         (setq max (max max current)
853               current 0))
854       (forward-line 1))
855     max))
856
857 (defun shr-collect-overlays ()
858   (save-excursion
859     (goto-char (point-min))
860     (let ((overlays nil))
861       (while (not (eobp))
862         (push (shr-overlays-in-region (point) (line-end-position))
863               overlays)
864         (forward-line 1))
865       (nreverse overlays))))
866
867 (defun shr-overlays-in-region (start end)
868   (let (result)
869     (dolist (overlay (overlays-in start end))
870       (push (list (if (> start (overlay-start overlay))
871                       (- end start)
872                     (- end (overlay-start overlay)))
873                   (if (< end (overlay-end overlay))
874                       0
875                     (- end (overlay-end overlay)))
876                   (overlay-properties overlay))
877             result))
878     (nreverse result)))
879
880 (defun shr-pro-rate-columns (columns)
881   (let ((total-percentage 0)
882         (widths (make-vector (length columns) 0)))
883     (dotimes (i (length columns))
884       (setq total-percentage (+ total-percentage (aref columns i))))
885     (setq total-percentage (/ 1.0 total-percentage))
886     (dotimes (i (length columns))
887       (aset widths i (max (truncate (* (aref columns i)
888                                        total-percentage
889                                        (- shr-width (1+ (length columns)))))
890                           10)))
891     widths))
892
893 ;; Return a summary of the number and shape of the TDs in the table.
894 (defun shr-column-specs (cont)
895   (let ((columns (make-vector (shr-max-columns cont) 1)))
896     (dolist (row cont)
897       (when (eq (car row) 'tr)
898         (let ((i 0))
899           (dolist (column (cdr row))
900             (when (memq (car column) '(td th))
901               (let ((width (cdr (assq :width (cdr column)))))
902                 (when (and width
903                            (string-match "\\([0-9]+\\)%" width))
904                   (aset columns i
905                         (/ (string-to-number (match-string 1 width))
906                            100.0))))
907               (setq i (1+ i)))))))
908     columns))
909
910 (defun shr-count (cont elem)
911   (let ((i 0))
912     (dolist (sub cont)
913       (when (eq (car sub) elem)
914         (setq i (1+ i))))
915     i))
916
917 (defun shr-max-columns (cont)
918   (let ((max 0))
919     (dolist (row cont)
920       (when (eq (car row) 'tr)
921         (setq max (max max (+ (shr-count (cdr row) 'td)
922                               (shr-count (cdr row) 'th))))))
923     max))
924
925 (provide 'shr)
926
927 ;;; shr.el ends here