bbb7ff18a46e59e95d59c32ff5dfeec4c3326748
[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             (goto-char start)
374             (shr-put-image data alt))))))
375   (kill-buffer (current-buffer)))
376
377 (defun shr-put-image (data alt)
378   (if (display-graphic-p)
379       (let ((image (ignore-errors
380                      (shr-rescale-image data))))
381         (when image
382           (insert-image image (or alt "*"))))
383     (insert alt)))
384
385 (defun shr-rescale-image (data)
386   (if (or (not (fboundp 'imagemagick-types))
387           (not (get-buffer-window (current-buffer))))
388       (create-image data nil t)
389     (let* ((image (create-image data nil t))
390            (size (image-size image t))
391            (width (car size))
392            (height (cdr size))
393            (edges (window-inside-pixel-edges
394                    (get-buffer-window (current-buffer))))
395            (window-width (truncate (* shr-max-image-proportion
396                                       (- (nth 2 edges) (nth 0 edges)))))
397            (window-height (truncate (* shr-max-image-proportion
398                                        (- (nth 3 edges) (nth 1 edges)))))
399            scaled-image)
400       (when (> height window-height)
401         (setq image (or (create-image data 'imagemagick t
402                                       :height window-height)
403                         image))
404         (setq size (image-size image t)))
405       (when (> (car size) window-width)
406         (setq image (or
407                      (create-image data 'imagemagick t
408                                    :width window-width)
409                      image)))
410       image)))
411
412 (defun shr-get-image-data (url)
413   "Get image data for URL.
414 Return a string with image data."
415   (with-temp-buffer
416     (mm-disable-multibyte)
417     (when (ignore-errors
418             (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
419             t)
420       (when (or (search-forward "\n\n" nil t)
421                 (search-forward "\r\n\r\n" nil t))
422         (buffer-substring (point) (point-max))))))
423
424 (defun shr-heading (cont &rest types)
425   (shr-ensure-paragraph)
426   (apply #'shr-fontize-cont cont types)
427   (shr-ensure-paragraph))
428
429 (defun shr-urlify (start url)
430   (widget-convert-button
431    'url-link start (point)
432    :help-echo url
433    :keymap shr-map
434    url)
435   (put-text-property start (point) 'shr-url url))
436
437 (defun shr-encode-url (url)
438   "Encode URL."
439   (browse-url-url-encode-chars url "[)$ ]"))
440
441 ;;; Tag-specific rendering rules.
442
443 (defun shr-tag-p (cont)
444   (shr-ensure-paragraph)
445   (shr-indent)
446   (shr-generic cont)
447   (shr-ensure-paragraph))
448
449 (defun shr-tag-div (cont)
450   (shr-ensure-newline)
451   (shr-indent)
452   (shr-generic cont)
453   (shr-ensure-newline))
454
455 (defun shr-tag-b (cont)
456   (shr-fontize-cont cont 'bold))
457
458 (defun shr-tag-i (cont)
459   (shr-fontize-cont cont 'italic))
460
461 (defun shr-tag-em (cont)
462   (shr-fontize-cont cont 'bold))
463
464 (defun shr-tag-strong (cont)
465   (shr-fontize-cont cont 'bold))
466
467 (defun shr-tag-u (cont)
468   (shr-fontize-cont cont 'underline))
469
470 (defun shr-tag-s (cont)
471   (shr-fontize-cont cont 'strike-through))
472
473 (defun shr-parse-style (style)
474   (when style
475     (let ((plist nil))
476       (dolist (elem (split-string style ";"))
477         (when elem
478           (setq elem (split-string elem ":"))
479           (when (and (car elem)
480                      (cadr elem))
481             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
482                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
483               (push (cons (intern name obarray)
484                           value)
485                     plist)))))
486       plist)))
487
488 (defun shr-tag-a (cont)
489   (let ((url (cdr (assq :href cont)))
490         (start (point))
491         shr-start)
492     (shr-generic cont)
493     (shr-urlify (or shr-start start) url)))
494
495 (defun shr-tag-object (cont)
496   (let ((start (point))
497         url)
498     (dolist (elem cont)
499       (when (eq (car elem) 'embed)
500         (setq url (or url (cdr (assq :src (cdr elem))))))
501       (when (and (eq (car elem) 'param)
502                  (equal (cdr (assq :name (cdr elem))) "movie"))
503         (setq url (or url (cdr (assq :value (cdr elem)))))))
504     (when url
505       (shr-insert " [multimedia] ")
506       (shr-urlify start url))
507     (shr-generic cont)))
508
509 (defun shr-tag-video (cont)
510   (let ((image (cdr (assq :poster cont)))
511         (url (cdr (assq :src cont)))
512         (start (point)))
513     (shr-tag-img nil image)
514     (shr-urlify start url)))
515
516 (defun shr-tag-img (cont &optional url)
517   (when (or url
518             (and cont
519                  (cdr (assq :src cont))))
520     (when (and (> (current-column) 0)
521                (not (eq shr-state 'image)))
522       (insert "\n"))
523     (let ((alt (cdr (assq :alt cont)))
524           (url (or url (cdr (assq :src cont)))))
525       (let ((start (point-marker)))
526         (when (zerop (length alt))
527           (setq alt "[img]"))
528         (cond
529          ((or (member (cdr (assq :height cont)) '("0" "1"))
530               (member (cdr (assq :width cont)) '("0" "1")))
531           ;; Ignore zero-sized or single-pixel images.
532           )
533          ((and (not shr-inhibit-images)
534                (string-match "\\`cid:" url))
535           (let ((url (substring url (match-end 0)))
536                 image)
537             (if (or (not shr-content-function)
538                     (not (setq image (funcall shr-content-function url))))
539                 (insert alt)
540               (shr-put-image image alt))))
541          ((or shr-inhibit-images
542               (and shr-blocked-images
543                    (string-match shr-blocked-images url)))
544           (setq shr-start (point))
545           (let ((shr-state 'space))
546             (if (> (length alt) 8)
547                 (shr-insert (substring alt 0 8))
548               (shr-insert alt))))
549          ((url-is-cached (shr-encode-url url))
550           (shr-put-image (shr-get-image-data url) alt))
551          (t
552           (insert alt)
553           (ignore-errors
554             (url-retrieve (shr-encode-url url) 'shr-image-fetched
555                           (list (current-buffer) start (point-marker))
556                           t))))
557         (put-text-property start (point) 'keymap shr-map)
558         (put-text-property start (point) 'shr-alt alt)
559         (put-text-property start (point) 'shr-image url)
560         (put-text-property start (point) 'help-echo alt)
561         (setq shr-state 'image)))))
562
563 (defun shr-tag-pre (cont)
564   (let ((shr-folding-mode 'none))
565     (shr-ensure-newline)
566     (shr-indent)
567     (shr-generic cont)
568     (shr-ensure-newline)))
569
570 (defun shr-tag-blockquote (cont)
571   (shr-ensure-paragraph)
572   (shr-indent)
573   (let ((shr-indentation (+ shr-indentation 4)))
574     (shr-generic cont))
575   (shr-ensure-paragraph))
576
577 (defun shr-tag-ul (cont)
578   (shr-ensure-paragraph)
579   (let ((shr-list-mode 'ul))
580     (shr-generic cont))
581   (shr-ensure-paragraph))
582
583 (defun shr-tag-ol (cont)
584   (shr-ensure-paragraph)
585   (let ((shr-list-mode 1))
586     (shr-generic cont))
587   (shr-ensure-paragraph))
588
589 (defun shr-tag-li (cont)
590   (shr-ensure-paragraph)
591   (shr-indent)
592   (let* ((bullet
593           (if (numberp shr-list-mode)
594               (prog1
595                   (format "%d " shr-list-mode)
596                 (setq shr-list-mode (1+ shr-list-mode)))
597             "* "))
598          (shr-indentation (+ shr-indentation (length bullet))))
599     (insert bullet)
600     (shr-generic cont)))
601
602 (defun shr-tag-br (cont)
603   (unless (bobp)
604     (insert "\n")
605     (shr-indent))
606   (shr-generic cont))
607
608 (defun shr-tag-h1 (cont)
609   (shr-heading cont 'bold 'underline))
610
611 (defun shr-tag-h2 (cont)
612   (shr-heading cont 'bold))
613
614 (defun shr-tag-h3 (cont)
615   (shr-heading cont 'italic))
616
617 (defun shr-tag-h4 (cont)
618   (shr-heading cont))
619
620 (defun shr-tag-h5 (cont)
621   (shr-heading cont))
622
623 (defun shr-tag-h6 (cont)
624   (shr-heading cont))
625
626 (defun shr-tag-hr (cont)
627   (shr-ensure-newline)
628   (insert (make-string shr-width shr-hr-line) "\n"))
629
630 ;;; Table rendering algorithm.
631
632 ;; Table rendering is the only complicated thing here.  We do this by
633 ;; first counting how many TDs there are in each TR, and registering
634 ;; how wide they think they should be ("width=45%", etc).  Then we
635 ;; render each TD separately (this is done in temporary buffers, so
636 ;; that we can use all the rendering machinery as if we were in the
637 ;; main buffer).  Now we know how much space each TD really takes, so
638 ;; we then render everything again with the new widths, and finally
639 ;; insert all these boxes into the main buffer.
640 (defun shr-tag-table-1 (cont)
641   (setq cont (or (cdr (assq 'tbody cont))
642                  cont))
643   (let* ((shr-inhibit-images t)
644          (shr-table-depth (1+ shr-table-depth))
645          (shr-kinsoku-shorten t)
646          ;; Find all suggested widths.
647          (columns (shr-column-specs cont))
648          ;; Compute how many characters wide each TD should be.
649          (suggested-widths (shr-pro-rate-columns columns))
650          ;; Do a "test rendering" to see how big each TD is (this can
651          ;; be smaller (if there's little text) or bigger (if there's
652          ;; unbreakable text).
653          (sketch (shr-make-table cont suggested-widths))
654          (sketch-widths (shr-table-widths sketch suggested-widths)))
655     ;; This probably won't work very well.
656     (when (> (+ (loop for width across sketch-widths
657                       summing (1+ width))
658                 shr-indentation 1)
659              (frame-width))
660       (setq truncate-lines t))
661     ;; Then render the table again with these new "hard" widths.
662     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
663   ;; Finally, insert all the images after the table.  The Emacs buffer
664   ;; model isn't strong enough to allow us to put the images actually
665   ;; into the tables.
666   (when (zerop shr-table-depth)
667     (dolist (elem (shr-find-elements cont 'img))
668       (shr-tag-img (cdr elem)))))
669
670 (defun shr-tag-table (cont)
671   (shr-ensure-paragraph)
672   (let* ((caption (cdr (assq 'caption cont)))
673          (header (cdr (assq 'thead cont)))
674          (body (or (cdr (assq 'tbody cont)) cont))
675          (footer (cdr (assq 'tfoot cont)))
676          (nheader (if header (shr-max-columns header)))
677          (nbody (if body (shr-max-columns body)))
678          (nfooter (if footer (shr-max-columns footer))))
679     (shr-tag-table-1
680      (nconc
681       (if caption `((tr (td ,@caption))))
682       (if header
683           (if footer
684               ;; hader + body + footer
685               (if (= nheader nbody)
686                   (if (= nbody nfooter)
687                       `((tr (td (table (tbody ,@header ,@body ,@footer)))))
688                     (nconc `((tr (td (table (tbody ,@header ,@body)))))
689                            (if (= nfooter 1)
690                                footer
691                              `((tr (td (table (tbody ,@footer))))))))
692                 (nconc `((tr (td (table (tbody ,@header)))))
693                        (if (= nbody nfooter)
694                            `((tr (td (table (tbody ,@body ,@footer)))))
695                          (nconc `((tr (td (table (tbody ,@body)))))
696                                 (if (= nfooter 1)
697                                     footer
698                                   `((tr (td (table (tbody ,@footer))))))))))
699             ;; header + body
700             (if (= nheader nbody)
701                 `((tr (td (table (tbody ,@header ,@body)))))
702               (if (= nheader 1)
703                   `(,@header (tr (td (table (tbody ,@body)))))
704                 `((tr (td (table (tbody ,@header))))
705                   (tr (td (table (tbody ,@body))))))))
706         (if footer
707             ;; body + footer
708             (if (= nbody nfooter)
709                 `((tr (td (table (tbody ,@body ,@footer)))))
710               (nconc `((tr (td (table (tbody ,@body)))))
711                      (if (= nfooter 1)
712                          footer
713                        `((tr (td (table (tbody ,@footer))))))))
714           (if caption
715               `((tr (td (table (tbody ,@body)))))
716             body)))))))
717
718 (defun shr-find-elements (cont type)
719   (let (result)
720     (dolist (elem cont)
721       (cond ((eq (car elem) type)
722              (push elem result))
723             ((consp (cdr elem))
724              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
725     (nreverse result)))
726
727 (defun shr-insert-table (table widths)
728   (shr-insert-table-ruler widths)
729   (dolist (row table)
730     (let ((start (point))
731           (height (let ((max 0))
732                     (dolist (column row)
733                       (setq max (max max (cadr column))))
734                     max)))
735       (dotimes (i height)
736         (shr-indent)
737         (insert "|\n"))
738       (dolist (column row)
739         (goto-char start)
740         (let ((lines (nth 2 column))
741               (overlay-lines (nth 3 column))
742               overlay overlay-line)
743           (dolist (line lines)
744             (setq overlay-line (pop overlay-lines))
745             (end-of-line)
746             (insert line "|")
747             (dolist (overlay overlay-line)
748               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
749                                      (- (point) (nth 1 overlay) 1)))
750                     (properties (nth 2 overlay)))
751                 (while properties
752                   (overlay-put o (pop properties) (pop properties)))))
753             (forward-line 1))
754           ;; Add blank lines at padding at the bottom of the TD,
755           ;; possibly.
756           (dotimes (i (- height (length lines)))
757             (end-of-line)
758             (insert (make-string (string-width (car lines)) ? ) "|")
759             (forward-line 1)))))
760     (shr-insert-table-ruler widths)))
761
762 (defun shr-insert-table-ruler (widths)
763   (when (and (bolp)
764              (> shr-indentation 0))
765     (shr-indent))
766   (insert shr-table-corner)
767   (dotimes (i (length widths))
768     (insert (make-string (aref widths i) shr-table-line) shr-table-corner))
769   (insert "\n"))
770
771 (defun shr-table-widths (table suggested-widths)
772   (let* ((length (length suggested-widths))
773          (widths (make-vector length 0))
774          (natural-widths (make-vector length 0)))
775     (dolist (row table)
776       (let ((i 0))
777         (dolist (column row)
778           (aset widths i (max (aref widths i)
779                               (car column)))
780           (aset natural-widths i (max (aref natural-widths i)
781                                       (cadr column)))
782           (setq i (1+ i)))))
783     (let ((extra (- (apply '+ (append suggested-widths nil))
784                     (apply '+ (append widths nil))))
785           (expanded-columns 0))
786       (when (> extra 0)
787         (dotimes (i length)
788           ;; If the natural width is wider than the rendered width, we
789           ;; want to allow the column to expand.
790           (when (> (aref natural-widths i) (aref widths i))
791             (setq expanded-columns (1+ expanded-columns))))
792         (dotimes (i length)
793           (when (> (aref natural-widths i) (aref widths i))
794             (aset widths i (min
795                             (1+ (aref natural-widths i))
796                             (+ (/ extra expanded-columns)
797                                (aref widths i))))))))
798     widths))
799
800 (defun shr-make-table (cont widths &optional fill)
801   (let ((trs nil))
802     (dolist (row cont)
803       (when (eq (car row) 'tr)
804         (let ((tds nil)
805               (columns (cdr row))
806               (i 0)
807               column)
808           (while (< i (length widths))
809             (setq column (pop columns))
810             (when (or (memq (car column) '(td th))
811                       (null column))
812               (push (shr-render-td (cdr column) (aref widths i) fill)
813                     tds)
814               (setq i (1+ i))))
815           (push (nreverse tds) trs))))
816     (nreverse trs)))
817
818 (defun shr-render-td (cont width fill)
819   (with-temp-buffer
820     (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
821       (if cache
822           (insert cache)
823         (let ((shr-width width)
824               (shr-indentation 0))
825           (shr-generic cont))
826         (delete-region
827          (point)
828          (+ (point)
829             (skip-chars-backward " \t\n")))
830         (push (cons (cons width cont) (buffer-string))
831               shr-content-cache)))
832     (goto-char (point-min))
833     (let ((max 0))
834       (while (not (eobp))
835         (end-of-line)
836         (setq max (max max (current-column)))
837         (forward-line 1))
838       (when fill
839         (goto-char (point-min))
840         ;; If the buffer is totally empty, then put a single blank
841         ;; line here.
842         (if (zerop (buffer-size))
843             (insert (make-string width ? ))
844           ;; Otherwise, fill the buffer.
845           (while (not (eobp))
846             (end-of-line)
847             (when (> (- width (current-column)) 0)
848               (insert (make-string (- width (current-column)) ? )))
849             (forward-line 1))))
850       (if fill
851           (list max
852                 (count-lines (point-min) (point-max))
853                 (split-string (buffer-string) "\n")
854                 (shr-collect-overlays))
855         (list max
856               (shr-natural-width))))))
857
858 (defun shr-natural-width ()
859   (goto-char (point-min))
860   (let ((current 0)
861         (max 0))
862     (while (not (eobp))
863       (end-of-line)
864       (setq current (+ current (current-column)))
865       (unless (get-text-property (point) 'shr-break)
866         (setq max (max max current)
867               current 0))
868       (forward-line 1))
869     max))
870
871 (defun shr-collect-overlays ()
872   (save-excursion
873     (goto-char (point-min))
874     (let ((overlays nil))
875       (while (not (eobp))
876         (push (shr-overlays-in-region (point) (line-end-position))
877               overlays)
878         (forward-line 1))
879       (nreverse overlays))))
880
881 (defun shr-overlays-in-region (start end)
882   (let (result)
883     (dolist (overlay (overlays-in start end))
884       (push (list (if (> start (overlay-start overlay))
885                       (- end start)
886                     (- end (overlay-start overlay)))
887                   (if (< end (overlay-end overlay))
888                       0
889                     (- end (overlay-end overlay)))
890                   (overlay-properties overlay))
891             result))
892     (nreverse result)))
893
894 (defun shr-pro-rate-columns (columns)
895   (let ((total-percentage 0)
896         (widths (make-vector (length columns) 0)))
897     (dotimes (i (length columns))
898       (setq total-percentage (+ total-percentage (aref columns i))))
899     (setq total-percentage (/ 1.0 total-percentage))
900     (dotimes (i (length columns))
901       (aset widths i (max (truncate (* (aref columns i)
902                                        total-percentage
903                                        (- shr-width (1+ (length columns)))))
904                           10)))
905     widths))
906
907 ;; Return a summary of the number and shape of the TDs in the table.
908 (defun shr-column-specs (cont)
909   (let ((columns (make-vector (shr-max-columns cont) 1)))
910     (dolist (row cont)
911       (when (eq (car row) 'tr)
912         (let ((i 0))
913           (dolist (column (cdr row))
914             (when (memq (car column) '(td th))
915               (let ((width (cdr (assq :width (cdr column)))))
916                 (when (and width
917                            (string-match "\\([0-9]+\\)%" width))
918                   (aset columns i
919                         (/ (string-to-number (match-string 1 width))
920                            100.0))))
921               (setq i (1+ i)))))))
922     columns))
923
924 (defun shr-count (cont elem)
925   (let ((i 0))
926     (dolist (sub cont)
927       (when (eq (car sub) elem)
928         (setq i (1+ i))))
929     i))
930
931 (defun shr-max-columns (cont)
932   (let ((max 0))
933     (dolist (row cont)
934       (when (eq (car row) 'tr)
935         (setq max (max max (+ (shr-count (cdr row) 'td)
936                               (shr-count (cdr row) 'th))))))
937     max))
938
939 (provide 'shr)
940
941 ;;; shr.el ends here