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