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