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