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