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