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