shr: Encode URL properly when fetching from cache
[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
36 (defgroup shr nil
37   "Simple HTML Renderer"
38   :group 'mail)
39
40 (defcustom shr-max-image-proportion 0.9
41   "How big pictures displayed are in relation to the window they're in.
42 A value of 0.7 means that they are allowed to take up 70% of the
43 width and height of the window.  If they are larger than this,
44 and Emacs supports it, then the images will be rescaled down to
45 fit these criteria."
46   :version "24.1"
47   :group 'shr
48   :type 'float)
49
50 (defcustom shr-blocked-images nil
51   "Images that have URLs matching this regexp will be blocked."
52   :version "24.1"
53   :group 'shr
54   :type 'regexp)
55
56 (defcustom shr-table-line ?-
57   "Character used to draw table line."
58   :group 'shr
59   :type 'char)
60
61 (defcustom shr-table-corner ?+
62   "Character used to draw table corner."
63   :group 'shr
64   :type 'char)
65
66 (defcustom shr-hr-line ?-
67   "Character used to draw hr line."
68   :group 'shr
69   :type 'char)
70
71 (defvar shr-content-function nil
72   "If bound, this should be a function that will return the content.
73 This is used for cid: URLs, and the function is called with the
74 cid: URL as the argument.")
75
76 (defvar shr-width 70
77   "Frame width to use for rendering.")
78
79 ;;; Internal variables.
80
81 (defvar shr-folding-mode nil)
82 (defvar shr-state nil)
83 (defvar shr-start nil)
84 (defvar shr-indentation 0)
85 (defvar shr-inhibit-images nil)
86 (defvar shr-list-mode nil)
87 (defvar shr-content-cache nil)
88
89 (defvar shr-map
90   (let ((map (make-sparse-keymap)))
91     (define-key map "a" 'shr-show-alt-text)
92     (define-key map "i" 'shr-browse-image)
93     (define-key map "I" 'shr-insert-image)
94     (define-key map "u" 'shr-copy-url)
95     (define-key map "v" 'shr-browse-url)
96     (define-key map "\r" 'shr-browse-url)
97     map))
98
99 ;; Public functions and commands.
100
101 ;;;###autoload
102 (defun shr-insert-document (dom)
103   (setq shr-content-cache nil)
104   (let ((shr-state nil)
105         (shr-start nil))
106     (shr-descend (shr-transform-dom dom))))
107
108 (defun shr-copy-url ()
109   "Copy the URL under point to the kill ring.
110 If called twice, then try to fetch the URL and see whether it
111 redirects somewhere else."
112   (interactive)
113   (let ((url (get-text-property (point) 'shr-url)))
114     (cond
115      ((not url)
116       (message "No URL under point"))
117      ;; Resolve redirected URLs.
118      ((equal url (car kill-ring))
119       (url-retrieve
120        url
121        (lambda (a)
122          (when (and (consp a)
123                     (eq (car a) :redirect))
124            (with-temp-buffer
125              (insert (cadr a))
126              (goto-char (point-min))
127              ;; Remove common tracking junk from the URL.
128              (when (re-search-forward ".utm_.*" nil t)
129                (replace-match "" t t))
130              (message "Copied %s" (buffer-string))
131              (copy-region-as-kill (point-min) (point-max)))))))
132      ;; Copy the URL to the kill ring.
133      (t
134       (with-temp-buffer
135         (insert url)
136         (copy-region-as-kill (point-min) (point-max))
137         (message "Copied %s" url))))))
138
139 (defun shr-show-alt-text ()
140   "Show the ALT text of the image under point."
141   (interactive)
142   (let ((text (get-text-property (point) 'shr-alt)))
143     (if (not text)
144         (message "No image under point")
145       (message "%s" text))))
146
147 (defun shr-browse-image ()
148   "Browse the image under point."
149   (interactive)
150   (let ((url (get-text-property (point) 'shr-image)))
151     (if (not url)
152         (message "No image under point")
153       (message "Browsing %s..." url)
154       (browse-url url))))
155
156 (defun shr-insert-image ()
157   "Insert the image under point into the buffer."
158   (interactive)
159   (let ((url (get-text-property (point) 'shr-image)))
160     (if (not url)
161         (message "No image under point")
162       (message "Inserting %s..." url)
163       (url-retrieve url 'shr-image-fetched
164                     (list (current-buffer) (1- (point)) (point-marker))
165                     t))))
166
167 ;;; Utility functions.
168
169 (defun shr-transform-dom (dom)
170   (let ((result (list (pop dom))))
171     (dolist (arg (pop dom))
172       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
173                   (cdr arg))
174             result))
175     (dolist (sub dom)
176       (if (stringp sub)
177           (push (cons :text sub) result)
178         (push (shr-transform-dom sub) result)))
179     (nreverse result)))
180
181 (defun shr-descend (dom)
182   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
183     (if (fboundp function)
184         (funcall function (cdr dom))
185       (shr-generic (cdr dom)))))
186
187 (defun shr-generic (cont)
188   (dolist (sub cont)
189     (cond
190      ((eq (car sub) :text)
191       (shr-insert (cdr sub)))
192      ((listp (cdr sub))
193       (shr-descend sub)))))
194
195 (defun shr-insert (text)
196   (when (and (eq shr-state 'image)
197              (not (string-match "\\`[ \t\n]+\\'" text)))
198     (insert "\n")
199     (setq shr-state nil))
200   (cond
201    ((eq shr-folding-mode 'none)
202     (insert text))
203    (t
204     (let ((first t)
205           column)
206       (when (and (string-match "\\`[ \t\n]" text)
207                  (not (bolp))
208                  (not (eq (char-after (1- (point))) ? )))
209         (insert " "))
210       (dolist (elem (split-string text))
211         (when (and (bolp)
212                    (> shr-indentation 0))
213           (shr-indent))
214         ;; The shr-start is a special variable that is used to pass
215         ;; upwards the first point in the buffer where the text really
216         ;; starts.
217         (unless shr-start
218           (setq shr-start (point)))
219         (insert elem)
220         (when (> (shr-current-column) shr-width)
221           (if (not (search-backward " " (line-beginning-position) t))
222               (insert "\n")
223             (delete-char 1)
224             (insert "\n")
225             (put-text-property (1- (point)) (point) 'shr-break t)
226             (when (> shr-indentation 0)
227               (shr-indent))
228             (end-of-line)))
229         (insert " "))
230       (unless (string-match "[ \t\n]\\'" text)
231         (delete-char -1))))))
232
233 (defun shr-find-fill-point ()
234   (let ((found nil))
235     (while (and (not found)
236                 (not (bolp)))
237       (when (or (eq (preceding-char) ? )
238                 (aref fill-find-break-point-function-table (preceding-char)))
239         (setq found (point)))
240       (backward-char 1))
241     (or found
242         (end-of-line))))
243
244 (defun shr-current-column ()
245   (let ((column 0))
246     (save-excursion
247       (beginning-of-line)
248       (while (not (eolp))
249         (incf column (char-width (following-char)))
250         (forward-char 1)))
251     column))
252
253 (defun shr-ensure-newline ()
254   (unless (zerop (current-column))
255     (insert "\n")))
256
257 (defun shr-ensure-paragraph ()
258   (unless (bobp)
259     (if (<= (current-column) shr-indentation)
260         (unless (save-excursion
261                   (forward-line -1)
262                   (looking-at " *$"))
263           (insert "\n"))
264       (if (save-excursion
265             (beginning-of-line)
266             (looking-at " *$"))
267           (insert "\n")
268         (insert "\n\n")))))
269
270 (defun shr-indent ()
271   (when (> shr-indentation 0)
272     (insert (make-string shr-indentation ? ))))
273
274 (defun shr-fontize-cont (cont &rest types)
275   (let (shr-start)
276     (shr-generic cont)
277     (dolist (type types)
278       (shr-add-font (or shr-start (point)) (point) type))))
279
280 (defun shr-add-font (start end type)
281   (let ((overlay (make-overlay start end)))
282     (overlay-put overlay 'face type)))
283
284 (defun shr-browse-url ()
285   "Browse the URL under point."
286   (interactive)
287   (let ((url (get-text-property (point) 'shr-url)))
288     (if (not url)
289         (message "No link under point")
290       (browse-url url))))
291
292 (defun shr-image-fetched (status buffer start end)
293   (when (and (buffer-name buffer)
294              (not (plist-get status :error)))
295     (url-store-in-cache (current-buffer))
296     (when (or (search-forward "\n\n" nil t)
297               (search-forward "\r\n\r\n" nil t))
298       (let ((data (buffer-substring (point) (point-max))))
299         (with-current-buffer buffer
300           (let ((alt (buffer-substring start end))
301                 (inhibit-read-only t))
302             (delete-region start end)
303             (shr-put-image data start alt))))))
304   (kill-buffer (current-buffer)))
305
306 (defun shr-put-image (data point alt)
307   (if (not (display-graphic-p))
308       (insert alt)
309     (let ((image (ignore-errors
310                    (shr-rescale-image data))))
311       (when image
312         (put-image image point alt)))))
313
314 (defun shr-rescale-image (data)
315   (if (or (not (fboundp 'imagemagick-types))
316           (not (get-buffer-window (current-buffer))))
317       (create-image data nil t)
318     (let* ((image (create-image data nil t))
319            (size (image-size image t))
320            (width (car size))
321            (height (cdr size))
322            (edges (window-inside-pixel-edges
323                    (get-buffer-window (current-buffer))))
324            (window-width (truncate (* shr-max-image-proportion
325                                       (- (nth 2 edges) (nth 0 edges)))))
326            (window-height (truncate (* shr-max-image-proportion
327                                        (- (nth 3 edges) (nth 1 edges)))))
328            scaled-image)
329       (when (> height window-height)
330         (setq image (or (create-image data 'imagemagick t
331                                       :height window-height)
332                         image))
333         (setq size (image-size image t)))
334       (when (> (car size) window-width)
335         (setq image (or
336                      (create-image data 'imagemagick t
337                                    :width window-width)
338                      image)))
339       image)))
340
341 (defun shr-get-image-data (url)
342   "Get image data for URL.
343 Return a string with image data."
344   (with-temp-buffer
345     (mm-disable-multibyte)
346     (when (ignore-errors
347             (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
348             t)
349       (when (or (search-forward "\n\n" nil t)
350                 (search-forward "\r\n\r\n" nil t))
351         (buffer-substring (point) (point-max))))))
352
353 (defun shr-heading (cont &rest types)
354   (shr-ensure-paragraph)
355   (apply #'shr-fontize-cont cont types)
356   (shr-ensure-paragraph))
357
358 ;;; Tag-specific rendering rules.
359
360 (defun shr-tag-p (cont)
361   (shr-ensure-paragraph)
362   (shr-indent)
363   (shr-generic cont)
364   (shr-ensure-paragraph))
365
366 (defun shr-tag-b (cont)
367   (shr-fontize-cont cont 'bold))
368
369 (defun shr-tag-i (cont)
370   (shr-fontize-cont cont 'italic))
371
372 (defun shr-tag-em (cont)
373   (shr-fontize-cont cont 'bold))
374
375 (defun shr-tag-u (cont)
376   (shr-fontize-cont cont 'underline))
377
378 (defun shr-tag-s (cont)
379   (shr-fontize-cont cont 'strike-through))
380
381 (defun shr-tag-a (cont)
382   (let ((url (cdr (assq :href cont)))
383         (start (point))
384         shr-start)
385     (shr-generic cont)
386     (widget-convert-button
387      'link (or shr-start start) (point)
388      :help-echo url)
389     (put-text-property (or shr-start start) (point) 'keymap shr-map)
390     (put-text-property (or shr-start start) (point) 'shr-url url)))
391
392 (defun shr-encode-url (url)
393   "Encode URL."
394   (browse-url-url-encode-chars url "[)$ ]"))
395
396 (defun shr-tag-img (cont)
397   (when (and (> (current-column) 0)
398              (not (eq shr-state 'image)))
399     (insert "\n"))
400   (let ((alt (cdr (assq :alt cont)))
401         (url (cdr (assq :src cont)))
402         (align (cdr (assq :align cont))))
403     (cond ((string= align "right")
404            (insert
405             (make-string (- fill-column (- (point) (line-beginning-position))) ? )))
406           ((string= align "center")
407            (insert
408             (make-string (- (/ fill-column 2) (- (point) (line-beginning-position))) ? ))))
409     (let ((start (point-marker)))
410       (when (zerop (length alt))
411         (setq alt "[img]"))
412       (cond
413        ((and (not shr-inhibit-images)
414              (string-match "\\`cid:" url))
415         (let ((url (substring url (match-end 0)))
416               image)
417           (if (or (not shr-content-function)
418                   (not (setq image (funcall shr-content-function url))))
419               (insert alt)
420             (shr-put-image image (point) alt))))
421        ((or shr-inhibit-images
422             (and shr-blocked-images
423                  (string-match shr-blocked-images url)))
424         (setq shr-start (point))
425         (let ((shr-state 'space))
426           (if (> (length alt) 8)
427               (shr-insert (substring alt 0 8))
428             (shr-insert alt))))
429        ((url-is-cached (shr-encode-url url))
430         (shr-put-image (shr-get-image-data url) (point) alt))
431        (t
432         (insert alt)
433         (ignore-errors
434           (url-retrieve (shr-encode-url url) 'shr-image-fetched
435                         (list (current-buffer) start (point-marker))
436                         t))))
437       (insert " ")
438       (put-text-property start (point) 'keymap shr-map)
439       (put-text-property start (point) 'shr-alt alt)
440       (put-text-property start (point) 'shr-image url)
441       (setq shr-state 'image))))
442
443 (defun shr-tag-pre (cont)
444   (let ((shr-folding-mode 'none))
445     (shr-ensure-newline)
446     (shr-indent)
447     (shr-generic cont)
448     (shr-ensure-newline)))
449
450 (defun shr-tag-blockquote (cont)
451   (shr-ensure-paragraph)
452   (shr-indent)
453   (let ((shr-indentation (+ shr-indentation 4)))
454     (shr-generic cont))
455   (shr-ensure-paragraph))
456
457 (defun shr-tag-ul (cont)
458   (shr-ensure-paragraph)
459   (let ((shr-list-mode 'ul))
460     (shr-generic cont))
461   (shr-ensure-paragraph))
462
463 (defun shr-tag-ol (cont)
464   (shr-ensure-paragraph)
465   (let ((shr-list-mode 1))
466     (shr-generic cont))
467   (shr-ensure-paragraph))
468
469 (defun shr-tag-li (cont)
470   (shr-ensure-paragraph)
471   (shr-indent)
472   (let* ((bullet
473           (if (numberp shr-list-mode)
474               (prog1
475                   (format "%d " shr-list-mode)
476                 (setq shr-list-mode (1+ shr-list-mode)))
477             "* "))
478          (shr-indentation (+ shr-indentation (length bullet))))
479     (insert bullet)
480     (shr-generic cont)))
481
482 (defun shr-tag-br (cont)
483   (unless (bobp)
484     (insert "\n")
485     (shr-indent))
486   (shr-generic cont))
487
488 (defun shr-tag-h1 (cont)
489   (shr-heading cont 'bold 'underline))
490
491 (defun shr-tag-h2 (cont)
492   (shr-heading cont 'bold))
493
494 (defun shr-tag-h3 (cont)
495   (shr-heading cont 'italic))
496
497 (defun shr-tag-h4 (cont)
498   (shr-heading cont))
499
500 (defun shr-tag-h5 (cont)
501   (shr-heading cont))
502
503 (defun shr-tag-h6 (cont)
504   (shr-heading cont))
505
506 (defun shr-tag-hr (cont)
507   (shr-ensure-newline)
508   (insert (make-string shr-width shr-hr-line) "\n"))
509
510 ;;; Table rendering algorithm.
511
512 ;; Table rendering is the only complicated thing here.  We do this by
513 ;; first counting how many TDs there are in each TR, and registering
514 ;; how wide they think they should be ("width=45%", etc).  Then we
515 ;; render each TD separately (this is done in temporary buffers, so
516 ;; that we can use all the rendering machinery as if we were in the
517 ;; main buffer).  Now we know how much space each TD really takes, so
518 ;; we then render everything again with the new widths, and finally
519 ;; insert all these boxes into the main buffer.
520 (defun shr-tag-table (cont)
521   (shr-ensure-paragraph)
522   (setq cont (or (cdr (assq 'tbody cont))
523                  cont))
524   (let* ((shr-inhibit-images t)
525          ;; Find all suggested widths.
526          (columns (shr-column-specs cont))
527          ;; Compute how many characters wide each TD should be.
528          (suggested-widths (shr-pro-rate-columns columns))
529          ;; Do a "test rendering" to see how big each TD is (this can
530          ;; be smaller (if there's little text) or bigger (if there's
531          ;; unbreakable text).
532          (sketch (shr-make-table cont suggested-widths))
533          (sketch-widths (shr-table-widths sketch suggested-widths)))
534     ;; Then render the table again with these new "hard" widths.
535     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
536   ;; Finally, insert all the images after the table.  The Emacs buffer
537   ;; model isn't strong enough to allow us to put the images actually
538   ;; into the tables.
539   (dolist (elem (shr-find-elements cont 'img))
540     (shr-tag-img (cdr elem))))
541
542 (defun shr-find-elements (cont type)
543   (let (result)
544     (dolist (elem cont)
545       (cond ((eq (car elem) type)
546              (push elem result))
547             ((consp (cdr elem))
548              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
549     (nreverse result)))
550
551 (defun shr-insert-table (table widths)
552   (shr-insert-table-ruler widths)
553   (dolist (row table)
554     (let ((start (point))
555           (height (let ((max 0))
556                     (dolist (column row)
557                       (setq max (max max (cadr column))))
558                     max)))
559       (dotimes (i height)
560         (shr-indent)
561         (insert "|\n"))
562       (dolist (column row)
563         (goto-char start)
564         (let ((lines (nth 2 column))
565               (overlay-lines (nth 3 column))
566               overlay overlay-line)
567           (dolist (line lines)
568             (setq overlay-line (pop overlay-lines))
569             (end-of-line)
570             (insert line "|")
571             (dolist (overlay overlay-line)
572               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
573                                      (- (point) (nth 1 overlay) 1)))
574                     (properties (nth 2 overlay)))
575                 (while properties
576                   (overlay-put o (pop properties) (pop properties)))))
577             (forward-line 1))
578           ;; Add blank lines at padding at the bottom of the TD,
579           ;; possibly.
580           (dotimes (i (- height (length lines)))
581             (end-of-line)
582             (insert (make-string (length (car lines)) ? ) "|")
583             (forward-line 1)))))
584     (shr-insert-table-ruler widths)))
585
586 (defun shr-insert-table-ruler (widths)
587   (shr-indent)
588   (insert shr-table-corner)
589   (dotimes (i (length widths))
590     (insert (make-string (aref widths i) shr-table-line) shr-table-corner))
591   (insert "\n"))
592
593 (defun shr-table-widths (table suggested-widths)
594   (let* ((length (length suggested-widths))
595          (widths (make-vector length 0))
596          (natural-widths (make-vector length 0)))
597     (dolist (row table)
598       (let ((i 0))
599         (dolist (column row)
600           (aset widths i (max (aref widths i)
601                               (car column)))
602           (aset natural-widths i (max (aref natural-widths i)
603                                       (cadr column)))
604           (setq i (1+ i)))))
605     (let ((extra (- (apply '+ (append suggested-widths nil))
606                     (apply '+ (append widths nil))))
607           (expanded-columns 0))
608       (when (> extra 0)
609         (dotimes (i length)
610           ;; If the natural width is wider than the rendered width, we
611           ;; want to allow the column to expand.
612           (when (> (aref natural-widths i) (aref widths i))
613             (setq expanded-columns (1+ expanded-columns))))
614         (dotimes (i length)
615           (when (> (aref natural-widths i) (aref widths i))
616             (aset widths i (min
617                             (1+ (aref natural-widths i))
618                             (+ (/ extra expanded-columns)
619                                (aref widths i))))))))
620     widths))
621
622 (defun shr-make-table (cont widths &optional fill)
623   (let ((trs nil))
624     (dolist (row cont)
625       (when (eq (car row) 'tr)
626         (let ((tds nil)
627               (columns (cdr row))
628               (i 0)
629               column)
630           (while (< i (length widths))
631             (setq column (pop columns))
632             (when (or (memq (car column) '(td th))
633                       (null column))
634               (push (shr-render-td (cdr column) (aref widths i) fill)
635                     tds)
636               (setq i (1+ i))))
637           (push (nreverse tds) trs))))
638     (nreverse trs)))
639
640 (defun shr-render-td (cont width fill)
641   (with-temp-buffer
642     (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
643       (if cache
644           (insert cache)
645         (let ((shr-width width)
646               (shr-indentation 0))
647           (shr-generic cont))
648         (delete-region
649          (point)
650          (+ (point)
651             (skip-chars-backward " \t\n")))
652         (push (cons (cons width cont) (buffer-string))
653               shr-content-cache)))
654     (goto-char (point-min))
655     (let ((max 0))
656       (while (not (eobp))
657         (end-of-line)
658         (setq max (max max (current-column)))
659         (forward-line 1))
660       (when fill
661         (goto-char (point-min))
662         ;; If the buffer is totally empty, then put a single blank
663         ;; line here.
664         (if (zerop (buffer-size))
665             (insert (make-string width ? ))
666           ;; Otherwise, fill the buffer.
667           (while (not (eobp))
668             (end-of-line)
669             (when (> (- width (current-column)) 0)
670               (insert (make-string (- width (current-column)) ? )))
671             (forward-line 1))))
672       (if fill
673           (list max
674                 (count-lines (point-min) (point-max))
675                 (split-string (buffer-string) "\n")
676                 (shr-collect-overlays))
677         (list max
678               (shr-natural-width))))))
679
680 (defun shr-natural-width ()
681   (goto-char (point-min))
682   (let ((current 0)
683         (max 0))
684     (while (not (eobp))
685       (end-of-line)
686       (setq current (+ current (current-column)))
687       (unless (get-text-property (point) 'shr-break)
688         (setq max (max max current)
689               current 0))
690       (forward-line 1))
691     max))
692
693 (defun shr-collect-overlays ()
694   (save-excursion
695     (goto-char (point-min))
696     (let ((overlays nil))
697       (while (not (eobp))
698         (push (shr-overlays-in-region (point) (line-end-position))
699               overlays)
700         (forward-line 1))
701       (nreverse overlays))))
702
703 (defun shr-overlays-in-region (start end)
704   (let (result)
705     (dolist (overlay (overlays-in start end))
706       (push (list (if (> start (overlay-start overlay))
707                       (- end start)
708                     (- end (overlay-start overlay)))
709                   (if (< end (overlay-end overlay))
710                       0
711                     (- end (overlay-end overlay)))
712                   (overlay-properties overlay))
713             result))
714     (nreverse result)))
715
716 (defun shr-pro-rate-columns (columns)
717   (let ((total-percentage 0)
718         (widths (make-vector (length columns) 0)))
719     (dotimes (i (length columns))
720       (setq total-percentage (+ total-percentage (aref columns i))))
721     (setq total-percentage (/ 1.0 total-percentage))
722     (dotimes (i (length columns))
723       (aset widths i (max (truncate (* (aref columns i)
724                                        total-percentage
725                                        (- shr-width (1+ (length columns)))))
726                           10)))
727     widths))
728
729 ;; Return a summary of the number and shape of the TDs in the table.
730 (defun shr-column-specs (cont)
731   (let ((columns (make-vector (shr-max-columns cont) 1)))
732     (dolist (row cont)
733       (when (eq (car row) 'tr)
734         (let ((i 0))
735           (dolist (column (cdr row))
736             (when (memq (car column) '(td th))
737               (let ((width (cdr (assq :width (cdr column)))))
738                 (when (and width
739                            (string-match "\\([0-9]+\\)%" width))
740                   (aset columns i
741                         (/ (string-to-number (match-string 1 width))
742                            100.0))))
743               (setq i (1+ i)))))))
744     columns))
745
746 (defun shr-count (cont elem)
747   (let ((i 0))
748     (dolist (sub cont)
749       (when (eq (car sub) elem)
750         (setq i (1+ i))))
751     i))
752
753 (defun shr-max-columns (cont)
754   (let ((max 0))
755     (dolist (row cont)
756       (when (eq (car row) 'tr)
757         (setq max (max max (+ (shr-count (cdr row) 'td)
758                               (shr-count (cdr row) 'th))))))
759     max))
760
761 (provide 'shr)
762
763 ;;; shr.el ends here