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