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