Make error reporting when doing `M-g' work again
[gnus] / lisp / shr.el
1 ;;; shr.el --- Simple HTML Renderer
2
3 ;; Copyright (C) 2010-2012 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-horizontal-line ?\s
57   "Character used to draw horizontal table lines."
58   :group 'shr
59   :type 'character)
60
61 (defcustom shr-table-vertical-line ?\s
62   "Character used to draw vertical table lines."
63   :group 'shr
64   :type 'character)
65
66 (defcustom shr-table-corner ?\s
67   "Character used to draw table corners."
68   :group 'shr
69   :type 'character)
70
71 (defcustom shr-hr-line ?-
72   "Character used to draw hr lines."
73   :group 'shr
74   :type 'character)
75
76 (defcustom shr-width fill-column
77   "Frame width to use for rendering.
78 May either be an integer specifying a fixed width in characters,
79 or nil, meaning that the full width of the window should be
80 used."
81   :type '(choice (integer :tag "Fixed width in characters")
82                  (const   :tag "Use the width of the window" nil))
83   :group 'shr)
84
85 (defvar shr-content-function nil
86   "If bound, this should be a function that will return the content.
87 This is used for cid: URLs, and the function is called with the
88 cid: URL as the argument.")
89
90 (defvar shr-put-image-function 'shr-put-image
91   "Function called to put image and alt string.")
92
93 (defface shr-strike-through '((t (:strike-through t)))
94   "Font for <s> elements."
95   :group 'shr)
96
97 (defface shr-link
98   '((t (:inherit link)))
99   "Font for link elements."
100   :group 'shr)
101
102 ;;; Internal variables.
103
104 (defvar shr-folding-mode nil)
105 (defvar shr-state nil)
106 (defvar shr-start nil)
107 (defvar shr-indentation 0)
108 (defvar shr-inhibit-images nil)
109 (defvar shr-list-mode nil)
110 (defvar shr-content-cache nil)
111 (defvar shr-kinsoku-shorten nil)
112 (defvar shr-table-depth 0)
113 (defvar shr-stylesheet nil)
114 (defvar shr-base nil)
115 (defvar shr-ignore-cache nil)
116
117 (defvar shr-map
118   (let ((map (make-sparse-keymap)))
119     (define-key map "a" 'shr-show-alt-text)
120     (define-key map "i" 'shr-browse-image)
121     (define-key map "I" 'shr-insert-image)
122     (define-key map "u" 'shr-copy-url)
123     (define-key map "v" 'shr-browse-url)
124     (define-key map "o" 'shr-save-contents)
125     (define-key map "\r" 'shr-browse-url)
126     map))
127
128 ;; Public functions and commands.
129
130 (defun shr-visit-file (file)
131   (interactive "fHTML file name: ")
132   (pop-to-buffer "*html*")
133   (erase-buffer)
134   (shr-insert-document
135    (with-temp-buffer
136      (insert-file-contents file)
137      (libxml-parse-html-region (point-min) (point-max))))
138   (goto-char (point-min)))
139
140 ;;;###autoload
141 (defun shr-insert-document (dom)
142   (setq shr-content-cache nil)
143   (let ((shr-state nil)
144         (shr-start nil)
145         (shr-base nil)
146         (shr-width (or shr-width (window-width))))
147     (shr-descend (shr-transform-dom dom))))
148
149 (defun shr-copy-url ()
150   "Copy the URL under point to the kill ring.
151 If called twice, then try to fetch the URL and see whether it
152 redirects somewhere else."
153   (interactive)
154   (let ((url (get-text-property (point) 'shr-url)))
155     (cond
156      ((not url)
157       (message "No URL under point"))
158      ;; Resolve redirected URLs.
159      ((equal url (car kill-ring))
160       (url-retrieve
161        url
162        (lambda (a)
163          (when (and (consp a)
164                     (eq (car a) :redirect))
165            (with-temp-buffer
166              (insert (cadr a))
167              (goto-char (point-min))
168              ;; Remove common tracking junk from the URL.
169              (when (re-search-forward ".utm_.*" nil t)
170                (replace-match "" t t))
171              (message "Copied %s" (buffer-string))
172              (copy-region-as-kill (point-min) (point-max)))))))
173      ;; Copy the URL to the kill ring.
174      (t
175       (with-temp-buffer
176         (insert url)
177         (copy-region-as-kill (point-min) (point-max))
178         (message "Copied %s" url))))))
179
180 (defun shr-show-alt-text ()
181   "Show the ALT text of the image under point."
182   (interactive)
183   (let ((text (get-text-property (point) 'shr-alt)))
184     (if (not text)
185         (message "No image under point")
186       (message "%s" text))))
187
188 (defun shr-browse-image (&optional copy-url)
189   "Browse the image under point.
190 If COPY-URL (the prefix if called interactively) is non-nil, copy
191 the URL of the image to the kill buffer instead."
192   (interactive "P")
193   (let ((url (get-text-property (point) 'image-url)))
194     (cond
195      ((not url)
196       (message "No image under point"))
197      (copy-url
198       (with-temp-buffer
199         (insert url)
200         (copy-region-as-kill (point-min) (point-max))
201         (message "Copied %s" url)))
202      (t
203       (message "Browsing %s..." url)
204       (browse-url url)))))
205
206 (defun shr-insert-image ()
207   "Insert the image under point into the buffer."
208   (interactive)
209   (let ((url (get-text-property (point) 'image-url)))
210     (if (not url)
211         (message "No image under point")
212       (message "Inserting %s..." url)
213       (url-retrieve url 'shr-image-fetched
214                     (list (current-buffer) (1- (point)) (point-marker))
215                     t))))
216
217 ;;; Utility functions.
218
219 (defun shr-transform-dom (dom)
220   (let ((result (list (pop dom))))
221     (dolist (arg (pop dom))
222       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
223                   (cdr arg))
224             result))
225     (dolist (sub dom)
226       (if (stringp sub)
227           (push (cons 'text sub) result)
228         (push (shr-transform-dom sub) result)))
229     (nreverse result)))
230
231 (defun shr-descend (dom)
232   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray))
233         (style (cdr (assq :style (cdr dom))))
234         (shr-stylesheet shr-stylesheet)
235         (start (point)))
236     (when style
237       (if (string-match "color" style)
238           (setq shr-stylesheet (nconc (shr-parse-style style)
239                                       shr-stylesheet))
240         (setq style nil)))
241     (if (fboundp function)
242         (funcall function (cdr dom))
243       (shr-generic (cdr dom)))
244     ;; If style is set, then this node has set the color.
245     (when style
246       (shr-colorize-region start (point)
247                            (cdr (assq 'color shr-stylesheet))
248                            (cdr (assq 'background-color shr-stylesheet))))))
249
250 (defun shr-generic (cont)
251   (dolist (sub cont)
252     (cond
253      ((eq (car sub) 'text)
254       (shr-insert (cdr sub)))
255      ((listp (cdr sub))
256       (shr-descend sub)))))
257
258 (defmacro shr-char-breakable-p (char)
259   "Return non-nil if a line can be broken before and after CHAR."
260   `(aref fill-find-break-point-function-table ,char))
261 (defmacro shr-char-nospace-p (char)
262   "Return non-nil if no space is required before and after CHAR."
263   `(aref fill-nospace-between-words-table ,char))
264
265 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
266 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
267 ;; parentheses, and so on, that should not be placed in the beginning
268 ;; of a line or the end of a line.
269 (defmacro shr-char-kinsoku-bol-p (char)
270   "Return non-nil if a line ought not to begin with CHAR."
271   `(aref (char-category-set ,char) ?>))
272 (defmacro shr-char-kinsoku-eol-p (char)
273   "Return non-nil if a line ought not to end with CHAR."
274   `(aref (char-category-set ,char) ?<))
275 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
276   (load "kinsoku" nil t))
277
278 (defun shr-insert (text)
279   (when (and (eq shr-state 'image)
280              (not (string-match "\\`[ \t\n]+\\'" text)))
281     (insert "\n")
282     (setq shr-state nil))
283   (cond
284    ((eq shr-folding-mode 'none)
285     (insert text))
286    (t
287     (when (and (string-match "\\`[ \t\n]" text)
288                (not (bolp))
289                (not (eq (char-after (1- (point))) ? )))
290       (insert " "))
291     (dolist (elem (split-string text))
292       (when (and (bolp)
293                  (> shr-indentation 0))
294         (shr-indent))
295       ;; No space is needed behind a wide character categorized as
296       ;; kinsoku-bol, between characters both categorized as nospace,
297       ;; or at the beginning of a line.
298       (let (prev)
299         (when (and (> (current-column) shr-indentation)
300                    (eq (preceding-char) ? )
301                    (or (= (line-beginning-position) (1- (point)))
302                        (and (shr-char-breakable-p
303                              (setq prev (char-after (- (point) 2))))
304                             (shr-char-kinsoku-bol-p prev))
305                        (and (shr-char-nospace-p prev)
306                             (shr-char-nospace-p (aref elem 0)))))
307           (delete-char -1)))
308       ;; The shr-start is a special variable that is used to pass
309       ;; upwards the first point in the buffer where the text really
310       ;; starts.
311       (unless shr-start
312         (setq shr-start (point)))
313       (insert elem)
314       (let (found)
315         (while (and (> (current-column) shr-width)
316                     (progn
317                       (setq found (shr-find-fill-point))
318                       (not (eolp))))
319           (when (eq (preceding-char) ? )
320             (delete-char -1))
321           (insert "\n")
322           (unless found
323             (put-text-property (1- (point)) (point) 'shr-break t)
324             ;; No space is needed at the beginning of a line.
325             (when (eq (following-char) ? )
326               (delete-char 1)))
327           (when (> shr-indentation 0)
328             (shr-indent))
329           (end-of-line))
330         (insert " ")))
331     (unless (string-match "[ \t\n]\\'" text)
332       (delete-char -1)))))
333
334 (defun shr-find-fill-point ()
335   (when (> (move-to-column shr-width) shr-width)
336     (backward-char 1))
337   (let ((bp (point))
338         failed)
339     (while (not (or (setq failed (= (current-column) shr-indentation))
340                     (eq (preceding-char) ? )
341                     (eq (following-char) ? )
342                     (shr-char-breakable-p (preceding-char))
343                     (shr-char-breakable-p (following-char))
344                     (if (eq (preceding-char) ?')
345                         (not (memq (char-after (- (point) 2))
346                                    (list nil ?\n ? )))
347                       (and (shr-char-kinsoku-bol-p (preceding-char))
348                            (shr-char-breakable-p (following-char))
349                            (not (shr-char-kinsoku-bol-p (following-char)))))
350                     (shr-char-kinsoku-eol-p (following-char))))
351       (backward-char 1))
352     (if (and (not (or failed (eolp)))
353              (eq (preceding-char) ?'))
354         (while (not (or (setq failed (eolp))
355                         (eq (following-char) ? )
356                         (shr-char-breakable-p (following-char))
357                         (shr-char-kinsoku-eol-p (following-char))))
358           (forward-char 1)))
359     (if failed
360         ;; There's no breakable point, so we give it up.
361         (let (found)
362           (goto-char bp)
363           (unless shr-kinsoku-shorten
364             (while (and (setq found (re-search-forward
365                                      "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
366                                      (line-end-position) 'move))
367                         (eq (preceding-char) ?')))
368             (if (and found (not (match-beginning 1)))
369                 (goto-char (match-beginning 0)))))
370       (or
371        (eolp)
372        ;; Don't put kinsoku-bol characters at the beginning of a line,
373        ;; or kinsoku-eol characters at the end of a line.
374        (cond
375         (shr-kinsoku-shorten
376          (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
377                      (shr-char-kinsoku-eol-p (preceding-char)))
378            (backward-char 1))
379          (when (setq failed (= (current-column) shr-indentation))
380            ;; There's no breakable point that doesn't violate kinsoku,
381            ;; so we look for the second best position.
382            (while (and (progn
383                          (forward-char 1)
384                          (<= (current-column) shr-width))
385                        (progn
386                          (setq bp (point))
387                          (shr-char-kinsoku-eol-p (following-char)))))
388            (goto-char bp)))
389         ((shr-char-kinsoku-eol-p (preceding-char))
390          (if (shr-char-kinsoku-eol-p (following-char))
391              ;; There are consecutive kinsoku-eol characters.
392              (setq failed t)
393            (let ((count 4))
394              (while
395                  (progn
396                    (backward-char 1)
397                    (and (> (setq count (1- count)) 0)
398                         (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
399                         (or (shr-char-kinsoku-eol-p (preceding-char))
400                             (shr-char-kinsoku-bol-p (following-char)))))))
401            (if (setq failed (= (current-column) shr-indentation))
402                ;; There's no breakable point that doesn't violate kinsoku,
403                ;; so we go to the second best position.
404                (if (looking-at "\\(\\c<+\\)\\c<")
405                    (goto-char (match-end 1))
406                  (forward-char 1)))))
407         (t
408          (if (shr-char-kinsoku-bol-p (preceding-char))
409              ;; There are consecutive kinsoku-bol characters.
410              (setq failed t)
411            (let ((count 4))
412              (while (and (>= (setq count (1- count)) 0)
413                          (shr-char-kinsoku-bol-p (following-char))
414                          (shr-char-breakable-p (following-char)))
415                (forward-char 1))))))
416        (when (eq (following-char) ? )
417          (forward-char 1))))
418     (not failed)))
419
420 (defun shr-expand-url (url)
421   (cond
422    ;; Absolute URL.
423    ((or (not url)
424         (string-match "\\`[a-z]*:" url)
425         (not shr-base))
426     url)
427    ((and (not (string-match "/\\'" shr-base))
428          (not (string-match "\\`/" url)))
429     (concat shr-base "/" url))
430    (t
431     (concat shr-base url))))
432
433 (defun shr-ensure-newline ()
434   (unless (zerop (current-column))
435     (insert "\n")))
436
437 (defun shr-ensure-paragraph ()
438   (unless (bobp)
439     (if (<= (current-column) shr-indentation)
440         (unless (save-excursion
441                   (forward-line -1)
442                   (looking-at " *$"))
443           (insert "\n"))
444       (if (save-excursion
445             (beginning-of-line)
446             (looking-at " *$"))
447           (insert "\n")
448         (insert "\n\n")))))
449
450 (defun shr-indent ()
451   (when (> shr-indentation 0)
452     (insert (make-string shr-indentation ? ))))
453
454 (defun shr-fontize-cont (cont &rest types)
455   (let (shr-start)
456     (shr-generic cont)
457     (dolist (type types)
458       (shr-add-font (or shr-start (point)) (point) type))))
459
460 ;; Add an overlay in the region, but avoid putting the font properties
461 ;; on blank text at the start of the line, and the newline at the end,
462 ;; to avoid ugliness.
463 (defun shr-add-font (start end type)
464   (save-excursion
465     (goto-char start)
466     (while (< (point) end)
467       (when (bolp)
468         (skip-chars-forward " "))
469       (let ((overlay (make-overlay (point) (min (line-end-position) end))))
470         (overlay-put overlay 'face type))
471       (if (< (line-end-position) end)
472           (forward-line 1)
473         (goto-char end)))))
474
475 (defun shr-browse-url ()
476   "Browse the URL under point."
477   (interactive)
478   (let ((url (get-text-property (point) 'shr-url)))
479     (cond
480      ((not url)
481       (message "No link under point"))
482      ((string-match "^mailto:" url)
483       (browse-url-mail url))
484      (t
485       (browse-url url)))))
486
487 (defun shr-save-contents (directory)
488   "Save the contents from URL in a file."
489   (interactive "DSave contents of URL to directory: ")
490   (let ((url (get-text-property (point) 'shr-url)))
491     (if (not url)
492         (message "No link under point")
493       (url-retrieve (shr-encode-url url)
494                     'shr-store-contents (list url directory)))))
495
496 (defun shr-store-contents (status url directory)
497   (unless (plist-get status :error)
498     (when (or (search-forward "\n\n" nil t)
499               (search-forward "\r\n\r\n" nil t))
500       (write-region (point) (point-max)
501                     (expand-file-name (file-name-nondirectory url)
502                                       directory)))))
503
504 (defun shr-image-fetched (status buffer start end)
505   (when (and (buffer-name buffer)
506              (not (plist-get status :error)))
507     (url-store-in-cache (current-buffer))
508     (when (or (search-forward "\n\n" nil t)
509               (search-forward "\r\n\r\n" nil t))
510       (let ((data (buffer-substring (point) (point-max))))
511         (with-current-buffer buffer
512           (save-excursion
513             (let ((alt (buffer-substring start end))
514                   (inhibit-read-only t))
515               (delete-region start end)
516               (goto-char start)
517               (funcall shr-put-image-function data alt)))))))
518   (kill-buffer (current-buffer)))
519
520 (defun shr-put-image (data alt)
521   "Put image DATA with a string ALT.  Return image."
522   (if (display-graphic-p)
523       (let ((image (ignore-errors
524                      (shr-rescale-image data))))
525         (when image
526           ;; When inserting big-ish pictures, put them at the
527           ;; beginning of the line.
528           (when (and (> (current-column) 0)
529                      (> (car (image-size image t)) 400))
530             (insert "\n"))
531           (insert-image image (or alt "*"))
532           (when (image-animated-p image)
533             (image-animate image nil 60)))
534         image)
535     (insert alt)))
536
537 (defun shr-rescale-image (data)
538   (let ((image (create-image data nil t :ascent 100)))
539     (if (or (not (fboundp 'imagemagick-types))
540             (not (get-buffer-window (current-buffer))))
541         image
542       (let* ((size (image-size image t))
543              (width (car size))
544              (height (cdr size))
545              (edges (window-inside-pixel-edges
546                      (get-buffer-window (current-buffer))))
547              (window-width (truncate (* shr-max-image-proportion
548                                         (- (nth 2 edges) (nth 0 edges)))))
549              (window-height (truncate (* shr-max-image-proportion
550                                          (- (nth 3 edges) (nth 1 edges)))))
551              scaled-image)
552         (when (> height window-height)
553           (setq image (or (create-image data 'imagemagick t
554                                         :height window-height
555                                         :ascent 100)
556                           image))
557           (setq size (image-size image t)))
558         (when (> (car size) window-width)
559           (setq image (or
560                        (create-image data 'imagemagick t
561                                      :width window-width
562                                      :ascent 100)
563                        image)))
564         image))))
565
566 ;; url-cache-extract autoloads url-cache.
567 (declare-function url-cache-create-filename "url-cache" (url))
568 (autoload 'mm-disable-multibyte "mm-util")
569 (autoload 'browse-url-mail "browse-url")
570
571 (defun shr-get-image-data (url)
572   "Get image data for URL.
573 Return a string with image data."
574   (with-temp-buffer
575     (mm-disable-multibyte)
576     (when (ignore-errors
577             (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
578             t)
579       (when (or (search-forward "\n\n" nil t)
580                 (search-forward "\r\n\r\n" nil t))
581         (buffer-substring (point) (point-max))))))
582
583 (defun shr-image-displayer (content-function)
584   "Return a function to display an image.
585 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
586 is an argument.  The function to be returned takes three arguments URL,
587 START, and END.  Note that START and END should be markers."
588   `(lambda (url start end)
589      (when url
590        (if (string-match "\\`cid:" url)
591            ,(when content-function
592               `(let ((image (funcall ,content-function
593                                      (substring url (match-end 0)))))
594                  (when image
595                    (goto-char start)
596                    (funcall shr-put-image-function
597                             image (buffer-substring start end))
598                    (delete-region (point) end))))
599          (url-retrieve url 'shr-image-fetched
600                        (list (current-buffer) start end)
601                        t)))))
602
603 (defun shr-heading (cont &rest types)
604   (shr-ensure-paragraph)
605   (apply #'shr-fontize-cont cont types)
606   (shr-ensure-paragraph))
607
608 (autoload 'widget-convert-button "wid-edit")
609
610 (defun shr-urlify (start url &optional title)
611   (widget-convert-button
612    'url-link start (point)
613    :help-echo (if title (format "%s (%s)" url title) url)
614    :keymap shr-map
615    url)
616   (shr-add-font start (point) 'shr-link)
617   (put-text-property start (point) 'shr-url url))
618
619 (defun shr-encode-url (url)
620   "Encode URL."
621   (browse-url-url-encode-chars url "[)$ ]"))
622
623 (autoload 'shr-color-visible "shr-color")
624 (autoload 'shr-color->hexadecimal "shr-color")
625
626 (defun shr-color-check (fg bg)
627   "Check that FG is visible on BG.
628 Returns (fg bg) with corrected values.
629 Returns nil if the colors that would be used are the default
630 ones, in case fg and bg are nil."
631   (when (or fg bg)
632     (let ((fixed (cond ((null fg) 'fg)
633                        ((null bg) 'bg))))
634       ;; Convert colors to hexadecimal, or set them to default.
635       (let ((fg (or (shr-color->hexadecimal fg)
636                     (frame-parameter nil 'foreground-color)))
637             (bg (or (shr-color->hexadecimal bg)
638                     (frame-parameter nil 'background-color))))
639         (cond ((eq fixed 'bg)
640                ;; Only return the new fg
641                (list nil (cadr (shr-color-visible bg fg t))))
642               ((eq fixed 'fg)
643                ;; Invert args and results and return only the new bg
644                (list (cadr (shr-color-visible fg bg t)) nil))
645               (t
646                (shr-color-visible bg fg)))))))
647
648 (defun shr-colorize-region (start end fg &optional bg)
649   (when (or fg bg)
650     (let ((new-colors (shr-color-check fg bg)))
651       (when new-colors
652         (when fg
653           (shr-put-color start end :foreground (cadr new-colors)))
654         (when bg
655           (shr-put-color start end :background (car new-colors))))
656       new-colors)))
657
658 ;; Put a color in the region, but avoid putting colors on blank
659 ;; text at the start of the line, and the newline at the end, to avoid
660 ;; ugliness.  Also, don't overwrite any existing color information,
661 ;; since this can be called recursively, and we want the "inner" color
662 ;; to win.
663 (defun shr-put-color (start end type color)
664   (save-excursion
665     (goto-char start)
666     (while (< (point) end)
667       (when (and (bolp)
668                  (not (eq type :background)))
669         (skip-chars-forward " "))
670       (when (> (line-end-position) (point))
671         (shr-put-color-1 (point) (min (line-end-position) end) type color))
672       (if (< (line-end-position) end)
673           (forward-line 1)
674         (goto-char end)))
675     (when (and (eq type :background)
676                (= shr-table-depth 0))
677       (shr-expand-newlines start end color))))
678
679 (defun shr-expand-newlines (start end color)
680   (save-restriction
681     ;; Skip past all white space at the start and ends.
682     (goto-char start)
683     (skip-chars-forward " \t\n")
684     (beginning-of-line)
685     (setq start (point))
686     (goto-char end)
687     (skip-chars-backward " \t\n")
688     (forward-line 1)
689     (setq end (point))
690     (narrow-to-region start end)
691     (let ((width (shr-natural-width))
692           column)
693       (goto-char (point-min))
694       (while (not (eobp))
695         (end-of-line)
696         (when (and (< (setq column (current-column)) width)
697                    (< (setq column (shr-previous-newline-padding-width column))
698                       width))
699           (let ((overlay (make-overlay (point) (1+ (point)))))
700             (overlay-put overlay 'before-string
701                          (concat
702                           (mapconcat
703                            (lambda (overlay)
704                              (let ((string (plist-get
705                                             (overlay-properties overlay)
706                                             'before-string)))
707                                (if (not string)
708                                    ""
709                                  (overlay-put overlay 'before-string "")
710                                  string)))
711                            (overlays-at (point))
712                            "")
713                           (propertize (make-string (- width column) ? )
714                                       'face (list :background color))))))
715         (forward-line 1)))))
716
717 (defun shr-previous-newline-padding-width (width)
718   (let ((overlays (overlays-at (point)))
719         (previous-width 0))
720     (if (null overlays)
721         width
722       (dolist (overlay overlays)
723         (setq previous-width
724               (+ previous-width
725                  (length (plist-get (overlay-properties overlay)
726                                     'before-string)))))
727       (+ width previous-width))))
728
729 (defun shr-put-color-1 (start end type color)
730   (let* ((old-props (get-text-property start 'face))
731          (do-put (and (listp old-props)
732                       (not (memq type old-props))))
733          change)
734     (while (< start end)
735       (setq change (next-single-property-change start 'face nil end))
736       (when do-put
737         (put-text-property start change 'face
738                            (nconc (list type color) old-props)))
739       (setq old-props (get-text-property change 'face))
740       (setq do-put (and (listp old-props)
741                         (not (memq type old-props))))
742       (setq start change))
743     (when (and do-put
744                (> end start))
745       (put-text-property start end 'face
746                          (nconc (list type color old-props))))))
747
748 ;;; Tag-specific rendering rules.
749
750 (defun shr-tag-body (cont)
751   (let* ((start (point))
752          (fgcolor (cdr (or (assq :fgcolor cont)
753                            (assq :text cont))))
754          (bgcolor (cdr (assq :bgcolor cont)))
755          (shr-stylesheet (list (cons 'color fgcolor)
756                                (cons 'background-color bgcolor))))
757     (shr-generic cont)
758     (shr-colorize-region start (point) fgcolor bgcolor)))
759
760 (defun shr-tag-style (cont)
761   )
762
763 (defun shr-tag-script (cont)
764   )
765
766 (defun shr-tag-comment (cont)
767   )
768
769 (defun shr-tag-sup (cont)
770   (let ((start (point)))
771     (shr-generic cont)
772     (put-text-property start (point) 'display '(raise 0.5))))
773
774 (defun shr-tag-sub (cont)
775   (let ((start (point)))
776     (shr-generic cont)
777     (put-text-property start (point) 'display '(raise -0.5))))
778
779 (defun shr-tag-label (cont)
780   (shr-generic cont)
781   (shr-ensure-paragraph))
782
783 (defun shr-tag-p (cont)
784   (shr-ensure-paragraph)
785   (shr-indent)
786   (shr-generic cont)
787   (shr-ensure-paragraph))
788
789 (defun shr-tag-div (cont)
790   (shr-ensure-newline)
791   (shr-indent)
792   (shr-generic cont)
793   (shr-ensure-newline))
794
795 (defun shr-tag-s (cont)
796   (shr-fontize-cont cont 'shr-strike-through))
797
798 (defun shr-tag-del (cont)
799   (shr-fontize-cont cont 'shr-strike-through))
800
801 (defun shr-tag-b (cont)
802   (shr-fontize-cont cont 'bold))
803
804 (defun shr-tag-i (cont)
805   (shr-fontize-cont cont 'italic))
806
807 (defun shr-tag-em (cont)
808   (shr-fontize-cont cont 'bold))
809
810 (defun shr-tag-strong (cont)
811   (shr-fontize-cont cont 'bold))
812
813 (defun shr-tag-u (cont)
814   (shr-fontize-cont cont 'underline))
815
816 (defun shr-parse-style (style)
817   (when style
818     (save-match-data
819       (when (string-match "\n" style)
820         (setq style (replace-match " " t t style))))
821     (let ((plist nil))
822       (dolist (elem (split-string style ";"))
823         (when elem
824           (setq elem (split-string elem ":"))
825           (when (and (car elem)
826                      (cadr elem))
827             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
828                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
829               (when (string-match " *!important\\'" value)
830                 (setq value (substring value 0 (match-beginning 0))))
831               (push (cons (intern name obarray)
832                           value)
833                     plist)))))
834       plist)))
835
836 (defun shr-tag-base (cont)
837   (setq shr-base (cdr (assq :href cont))))
838
839 (defun shr-tag-a (cont)
840   (let ((url (cdr (assq :href cont)))
841         (title (cdr (assq :title cont)))
842         (start (point))
843         shr-start)
844     (shr-generic cont)
845     (shr-urlify (or shr-start start) (shr-expand-url url) title)))
846
847 (defun shr-tag-object (cont)
848   (let ((start (point))
849         url)
850     (dolist (elem cont)
851       (when (eq (car elem) 'embed)
852         (setq url (or url (cdr (assq :src (cdr elem))))))
853       (when (and (eq (car elem) 'param)
854                  (equal (cdr (assq :name (cdr elem))) "movie"))
855         (setq url (or url (cdr (assq :value (cdr elem)))))))
856     (when url
857       (shr-insert " [multimedia] ")
858       (shr-urlify start (shr-expand-url url)))
859     (shr-generic cont)))
860
861 (defun shr-tag-video (cont)
862   (let ((image (cdr (assq :poster cont)))
863         (url (cdr (assq :src cont)))
864         (start (point)))
865     (shr-tag-img nil image)
866     (shr-urlify start (shr-expand-url url))))
867
868 (defun shr-tag-img (cont &optional url)
869   (when (or url
870             (and cont
871                  (cdr (assq :src cont))))
872     (when (and (> (current-column) 0)
873                (not (eq shr-state 'image)))
874       (insert "\n"))
875     (let ((alt (cdr (assq :alt cont)))
876           (url (shr-expand-url (or url (cdr (assq :src cont))))))
877       (let ((start (point-marker)))
878         (when (zerop (length alt))
879           (setq alt "*"))
880         (cond
881          ((or (member (cdr (assq :height cont)) '("0" "1"))
882               (member (cdr (assq :width cont)) '("0" "1")))
883           ;; Ignore zero-sized or single-pixel images.
884           )
885          ((and (not shr-inhibit-images)
886                (string-match "\\`cid:" url))
887           (let ((url (substring url (match-end 0)))
888                 image)
889             (if (or (not shr-content-function)
890                     (not (setq image (funcall shr-content-function url))))
891                 (insert alt)
892               (funcall shr-put-image-function image alt))))
893          ((or shr-inhibit-images
894               (and shr-blocked-images
895                    (string-match shr-blocked-images url)))
896           (setq shr-start (point))
897           (let ((shr-state 'space))
898             (if (> (string-width alt) 8)
899                 (shr-insert (truncate-string-to-width alt 8))
900               (shr-insert alt))))
901          ((and (not shr-ignore-cache)
902                (url-is-cached (shr-encode-url url)))
903           (funcall shr-put-image-function (shr-get-image-data url) alt))
904          (t
905           (insert alt " ")
906           (when (and shr-ignore-cache
907                      (url-is-cached (shr-encode-url url)))
908             (let ((file (url-cache-create-filename (shr-encode-url url))))
909               (when (file-exists-p file)
910                 (delete-file file))))
911           (funcall
912            (if (fboundp 'url-queue-retrieve)
913                'url-queue-retrieve
914              'url-retrieve)
915            (shr-encode-url url) 'shr-image-fetched
916            (list (current-buffer) start (set-marker (make-marker) (1- (point))))
917            t)))
918         (when (zerop shr-table-depth) ;; We are not in a table.
919           (put-text-property start (point) 'keymap shr-map)
920           (put-text-property start (point) 'shr-alt alt)
921           (put-text-property start (point) 'image-url url)
922           (put-text-property start (point) 'image-displayer
923                              (shr-image-displayer shr-content-function))
924           (put-text-property start (point) 'help-echo alt))
925         (setq shr-state 'image)))))
926
927 (defun shr-tag-pre (cont)
928   (let ((shr-folding-mode 'none))
929     (shr-ensure-newline)
930     (shr-indent)
931     (shr-generic cont)
932     (shr-ensure-newline)))
933
934 (defun shr-tag-blockquote (cont)
935   (shr-ensure-paragraph)
936   (shr-indent)
937   (let ((shr-indentation (+ shr-indentation 4)))
938     (shr-generic cont))
939   (shr-ensure-paragraph))
940
941 (defun shr-tag-ul (cont)
942   (shr-ensure-paragraph)
943   (let ((shr-list-mode 'ul))
944     (shr-generic cont))
945   (shr-ensure-paragraph))
946
947 (defun shr-tag-ol (cont)
948   (shr-ensure-paragraph)
949   (let ((shr-list-mode 1))
950     (shr-generic cont))
951   (shr-ensure-paragraph))
952
953 (defun shr-tag-li (cont)
954   (shr-ensure-paragraph)
955   (shr-indent)
956   (let* ((bullet
957           (if (numberp shr-list-mode)
958               (prog1
959                   (format "%d " shr-list-mode)
960                 (setq shr-list-mode (1+ shr-list-mode)))
961             "* "))
962          (shr-indentation (+ shr-indentation (length bullet))))
963     (insert bullet)
964     (shr-generic cont)))
965
966 (defun shr-tag-br (cont)
967   (unless (bobp)
968     (insert "\n")
969     (shr-indent))
970   (shr-generic cont))
971
972 (defun shr-tag-h1 (cont)
973   (shr-heading cont 'bold 'underline))
974
975 (defun shr-tag-h2 (cont)
976   (shr-heading cont 'bold))
977
978 (defun shr-tag-h3 (cont)
979   (shr-heading cont 'italic))
980
981 (defun shr-tag-h4 (cont)
982   (shr-heading cont))
983
984 (defun shr-tag-h5 (cont)
985   (shr-heading cont))
986
987 (defun shr-tag-h6 (cont)
988   (shr-heading cont))
989
990 (defun shr-tag-hr (cont)
991   (shr-ensure-newline)
992   (insert (make-string shr-width shr-hr-line) "\n"))
993
994 (defun shr-tag-title (cont)
995   (shr-heading cont 'bold 'underline))
996
997 (defun shr-tag-font (cont)
998   (let* ((start (point))
999          (color (cdr (assq :color cont)))
1000          (shr-stylesheet (nconc (list (cons 'color color))
1001                                 shr-stylesheet)))
1002     (shr-generic cont)
1003     (when color
1004       (shr-colorize-region start (point) color
1005                            (cdr (assq 'background-color shr-stylesheet))))))
1006
1007 ;;; Table rendering algorithm.
1008
1009 ;; Table rendering is the only complicated thing here.  We do this by
1010 ;; first counting how many TDs there are in each TR, and registering
1011 ;; how wide they think they should be ("width=45%", etc).  Then we
1012 ;; render each TD separately (this is done in temporary buffers, so
1013 ;; that we can use all the rendering machinery as if we were in the
1014 ;; main buffer).  Now we know how much space each TD really takes, so
1015 ;; we then render everything again with the new widths, and finally
1016 ;; insert all these boxes into the main buffer.
1017 (defun shr-tag-table-1 (cont)
1018   (setq cont (or (cdr (assq 'tbody cont))
1019                  cont))
1020   (let* ((shr-inhibit-images t)
1021          (shr-table-depth (1+ shr-table-depth))
1022          (shr-kinsoku-shorten t)
1023          ;; Find all suggested widths.
1024          (columns (shr-column-specs cont))
1025          ;; Compute how many characters wide each TD should be.
1026          (suggested-widths (shr-pro-rate-columns columns))
1027          ;; Do a "test rendering" to see how big each TD is (this can
1028          ;; be smaller (if there's little text) or bigger (if there's
1029          ;; unbreakable text).
1030          (sketch (shr-make-table cont suggested-widths))
1031          (sketch-widths (shr-table-widths sketch suggested-widths)))
1032     ;; This probably won't work very well.
1033     (when (> (+ (loop for width across sketch-widths
1034                       summing (1+ width))
1035                 shr-indentation 1)
1036              (frame-width))
1037       (setq truncate-lines t))
1038     ;; Then render the table again with these new "hard" widths.
1039     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
1040   ;; Finally, insert all the images after the table.  The Emacs buffer
1041   ;; model isn't strong enough to allow us to put the images actually
1042   ;; into the tables.
1043   (when (zerop shr-table-depth)
1044     (dolist (elem (shr-find-elements cont 'img))
1045       (shr-tag-img (cdr elem)))))
1046
1047 (defun shr-tag-table (cont)
1048   (shr-ensure-paragraph)
1049   (let* ((caption (cdr (assq 'caption cont)))
1050          (header (cdr (assq 'thead cont)))
1051          (body (or (cdr (assq 'tbody cont)) cont))
1052          (footer (cdr (assq 'tfoot cont)))
1053          (bgcolor (cdr (assq :bgcolor cont)))
1054          (start (point))
1055          (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1056                                 shr-stylesheet))
1057          (nheader (if header (shr-max-columns header)))
1058          (nbody (if body (shr-max-columns body)))
1059          (nfooter (if footer (shr-max-columns footer))))
1060     (if (and (not caption)
1061              (not header)
1062              (not (cdr (assq 'tbody cont)))
1063              (not (cdr (assq 'tr cont)))
1064              (not footer))
1065         ;; The table is totally invalid and just contains random junk.
1066         ;; Try to output it anyway.
1067         (shr-generic cont)
1068       ;; It's a real table, so render it.
1069       (shr-tag-table-1
1070        (nconc
1071         (if caption `((tr (td ,@caption))))
1072         (if header
1073             (if footer
1074                 ;; hader + body + footer
1075                 (if (= nheader nbody)
1076                     (if (= nbody nfooter)
1077                         `((tr (td (table (tbody ,@header ,@body ,@footer)))))
1078                       (nconc `((tr (td (table (tbody ,@header ,@body)))))
1079                              (if (= nfooter 1)
1080                                  footer
1081                                `((tr (td (table (tbody ,@footer))))))))
1082                   (nconc `((tr (td (table (tbody ,@header)))))
1083                          (if (= nbody nfooter)
1084                              `((tr (td (table (tbody ,@body ,@footer)))))
1085                            (nconc `((tr (td (table (tbody ,@body)))))
1086                                   (if (= nfooter 1)
1087                                       footer
1088                                     `((tr (td (table (tbody ,@footer))))))))))
1089               ;; header + body
1090               (if (= nheader nbody)
1091                   `((tr (td (table (tbody ,@header ,@body)))))
1092                 (if (= nheader 1)
1093                     `(,@header (tr (td (table (tbody ,@body)))))
1094                   `((tr (td (table (tbody ,@header))))
1095                     (tr (td (table (tbody ,@body))))))))
1096           (if footer
1097               ;; body + footer
1098               (if (= nbody nfooter)
1099                   `((tr (td (table (tbody ,@body ,@footer)))))
1100                 (nconc `((tr (td (table (tbody ,@body)))))
1101                        (if (= nfooter 1)
1102                            footer
1103                          `((tr (td (table (tbody ,@footer))))))))
1104             (if caption
1105                 `((tr (td (table (tbody ,@body)))))
1106               body))))))
1107     (when bgcolor
1108       (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1109                            bgcolor))))
1110
1111 (defun shr-find-elements (cont type)
1112   (let (result)
1113     (dolist (elem cont)
1114       (cond ((eq (car elem) type)
1115              (push elem result))
1116             ((consp (cdr elem))
1117              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
1118     (nreverse result)))
1119
1120 (defun shr-insert-table (table widths)
1121   (shr-insert-table-ruler widths)
1122   (dolist (row table)
1123     (let ((start (point))
1124           (height (let ((max 0))
1125                     (dolist (column row)
1126                       (setq max (max max (cadr column))))
1127                     max)))
1128       (dotimes (i height)
1129         (shr-indent)
1130         (insert shr-table-vertical-line "\n"))
1131       (dolist (column row)
1132         (goto-char start)
1133         (let ((lines (nth 2 column))
1134               (overlay-lines (nth 3 column))
1135               overlay overlay-line)
1136           (dolist (line lines)
1137             (setq overlay-line (pop overlay-lines))
1138             (end-of-line)
1139             (insert line shr-table-vertical-line)
1140             (dolist (overlay overlay-line)
1141               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
1142                                      (- (point) (nth 1 overlay) 1)))
1143                     (properties (nth 2 overlay)))
1144                 (while properties
1145                   (overlay-put o (pop properties) (pop properties)))))
1146             (forward-line 1))
1147           ;; Add blank lines at padding at the bottom of the TD,
1148           ;; possibly.
1149           (dotimes (i (- height (length lines)))
1150             (end-of-line)
1151             (let ((start (point)))
1152               (insert (make-string (string-width (car lines)) ? )
1153                       shr-table-vertical-line)
1154               (when (nth 4 column)
1155                 (shr-put-color start (1- (point)) :background (nth 4 column))))
1156             (forward-line 1)))))
1157     (shr-insert-table-ruler widths)))
1158
1159 (defun shr-insert-table-ruler (widths)
1160   (when (and (bolp)
1161              (> shr-indentation 0))
1162     (shr-indent))
1163   (insert shr-table-corner)
1164   (dotimes (i (length widths))
1165     (insert (make-string (aref widths i) shr-table-horizontal-line)
1166             shr-table-corner))
1167   (insert "\n"))
1168
1169 (defun shr-table-widths (table suggested-widths)
1170   (let* ((length (length suggested-widths))
1171          (widths (make-vector length 0))
1172          (natural-widths (make-vector length 0)))
1173     (dolist (row table)
1174       (let ((i 0))
1175         (dolist (column row)
1176           (aset widths i (max (aref widths i)
1177                               (car column)))
1178           (aset natural-widths i (max (aref natural-widths i)
1179                                       (cadr column)))
1180           (setq i (1+ i)))))
1181     (let ((extra (- (apply '+ (append suggested-widths nil))
1182                     (apply '+ (append widths nil))))
1183           (expanded-columns 0))
1184       (when (> extra 0)
1185         (dotimes (i length)
1186           ;; If the natural width is wider than the rendered width, we
1187           ;; want to allow the column to expand.
1188           (when (> (aref natural-widths i) (aref widths i))
1189             (setq expanded-columns (1+ expanded-columns))))
1190         (dotimes (i length)
1191           (when (> (aref natural-widths i) (aref widths i))
1192             (aset widths i (min
1193                             (1+ (aref natural-widths i))
1194                             (+ (/ extra expanded-columns)
1195                                (aref widths i))))))))
1196     widths))
1197
1198 (defun shr-make-table (cont widths &optional fill)
1199   (let ((trs nil))
1200     (dolist (row cont)
1201       (when (eq (car row) 'tr)
1202         (let ((tds nil)
1203               (columns (cdr row))
1204               (i 0)
1205               column)
1206           (while (< i (length widths))
1207             (setq column (pop columns))
1208             (when (or (memq (car column) '(td th))
1209                       (null column))
1210               (push (shr-render-td (cdr column) (aref widths i) fill)
1211                     tds)
1212               (setq i (1+ i))))
1213           (push (nreverse tds) trs))))
1214     (nreverse trs)))
1215
1216 (defun shr-render-td (cont width fill)
1217   (with-temp-buffer
1218     (let ((bgcolor (cdr (assq :bgcolor cont)))
1219           (fgcolor (cdr (assq :fgcolor cont)))
1220           (style (cdr (assq :style cont)))
1221           (shr-stylesheet shr-stylesheet)
1222           overlays actual-colors)
1223       (when style
1224         (setq style (and (string-match "color" style)
1225                          (shr-parse-style style))))
1226       (when bgcolor
1227         (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1228       (when fgcolor
1229         (setq style (nconc (list (cons 'color fgcolor)) style)))
1230       (when style
1231         (setq shr-stylesheet (append style shr-stylesheet)))
1232       (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
1233         (if cache
1234             (progn
1235               (insert (car cache))
1236               (let ((end (length (car cache))))
1237                 (dolist (overlay (cadr cache))
1238                   (let ((new-overlay
1239                          (make-overlay (1+ (- end (nth 0 overlay)))
1240                                        (1+ (- end (nth 1 overlay)))))
1241                         (properties (nth 2 overlay)))
1242                     (while properties
1243                       (overlay-put new-overlay
1244                                    (pop properties) (pop properties)))))))
1245           (let ((shr-width width)
1246                 (shr-indentation 0))
1247             (shr-descend (cons 'td cont)))
1248           (delete-region
1249            (point)
1250            (+ (point)
1251               (skip-chars-backward " \t\n")))
1252           (push (list (cons width cont) (buffer-string)
1253                       (shr-overlays-in-region (point-min) (point-max)))
1254                 shr-content-cache)))
1255       (goto-char (point-min))
1256       (let ((max 0))
1257         (while (not (eobp))
1258           (end-of-line)
1259           (setq max (max max (current-column)))
1260           (forward-line 1))
1261         (when fill
1262           (goto-char (point-min))
1263           ;; If the buffer is totally empty, then put a single blank
1264           ;; line here.
1265           (if (zerop (buffer-size))
1266               (insert (make-string width ? ))
1267             ;; Otherwise, fill the buffer.
1268             (while (not (eobp))
1269               (end-of-line)
1270               (when (> (- width (current-column)) 0)
1271                 (insert (make-string (- width (current-column)) ? )))
1272               (forward-line 1)))
1273           (when style
1274             (setq actual-colors
1275                   (shr-colorize-region
1276                    (point-min) (point-max)
1277                    (cdr (assq 'color shr-stylesheet))
1278                    (cdr (assq 'background-color shr-stylesheet))))))
1279         (if fill
1280             (list max
1281                   (count-lines (point-min) (point-max))
1282                   (split-string (buffer-string) "\n")
1283                   (shr-collect-overlays)
1284                   (car actual-colors))
1285           (list max
1286                 (shr-natural-width)))))))
1287
1288 (defun shr-natural-width ()
1289   (goto-char (point-min))
1290   (let ((current 0)
1291         (max 0))
1292     (while (not (eobp))
1293       (end-of-line)
1294       (setq current (+ current (current-column)))
1295       (unless (get-text-property (point) 'shr-break)
1296         (setq max (max max current)
1297               current 0))
1298       (forward-line 1))
1299     max))
1300
1301 (defun shr-collect-overlays ()
1302   (save-excursion
1303     (goto-char (point-min))
1304     (let ((overlays nil))
1305       (while (not (eobp))
1306         (push (shr-overlays-in-region (point) (line-end-position))
1307               overlays)
1308         (forward-line 1))
1309       (nreverse overlays))))
1310
1311 (defun shr-overlays-in-region (start end)
1312   (let (result)
1313     (dolist (overlay (overlays-in start end))
1314       (push (list (if (> start (overlay-start overlay))
1315                       (- end start)
1316                     (- end (overlay-start overlay)))
1317                   (if (< end (overlay-end overlay))
1318                       0
1319                     (- end (overlay-end overlay)))
1320                   (overlay-properties overlay))
1321             result))
1322     (nreverse result)))
1323
1324 (defun shr-pro-rate-columns (columns)
1325   (let ((total-percentage 0)
1326         (widths (make-vector (length columns) 0)))
1327     (dotimes (i (length columns))
1328       (setq total-percentage (+ total-percentage (aref columns i))))
1329     (setq total-percentage (/ 1.0 total-percentage))
1330     (dotimes (i (length columns))
1331       (aset widths i (max (truncate (* (aref columns i)
1332                                        total-percentage
1333                                        (- shr-width (1+ (length columns)))))
1334                           10)))
1335     widths))
1336
1337 ;; Return a summary of the number and shape of the TDs in the table.
1338 (defun shr-column-specs (cont)
1339   (let ((columns (make-vector (shr-max-columns cont) 1)))
1340     (dolist (row cont)
1341       (when (eq (car row) 'tr)
1342         (let ((i 0))
1343           (dolist (column (cdr row))
1344             (when (memq (car column) '(td th))
1345               (let ((width (cdr (assq :width (cdr column)))))
1346                 (when (and width
1347                            (string-match "\\([0-9]+\\)%" width))
1348                   (aset columns i
1349                         (/ (string-to-number (match-string 1 width))
1350                            100.0))))
1351               (setq i (1+ i)))))))
1352     columns))
1353
1354 (defun shr-count (cont elem)
1355   (let ((i 0))
1356     (dolist (sub cont)
1357       (when (eq (car sub) elem)
1358         (setq i (1+ i))))
1359     i))
1360
1361 (defun shr-max-columns (cont)
1362   (let ((max 0))
1363     (dolist (row cont)
1364       (when (eq (car row) 'tr)
1365         (setq max (max max (+ (shr-count (cdr row) 'td)
1366                               (shr-count (cdr row) 'th))))))
1367     max))
1368
1369 (provide 'shr)
1370
1371 ;;; shr.el ends here