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