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