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