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