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