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