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