Inhibit cookies when fetching pictures
[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        nil t))
193      ;; Copy the URL to the kill ring.
194      (t
195       (with-temp-buffer
196         (insert url)
197         (copy-region-as-kill (point-min) (point-max))
198         (message "Copied %s" url))))))
199
200 (defun shr-show-alt-text ()
201   "Show the ALT text of the image under point."
202   (interactive)
203   (let ((text (get-text-property (point) 'shr-alt)))
204     (if (not text)
205         (message "No image under point")
206       (message "%s" text))))
207
208 (defun shr-browse-image (&optional copy-url)
209   "Browse the image under point.
210 If COPY-URL (the prefix if called interactively) is non-nil, copy
211 the URL of the image to the kill buffer instead."
212   (interactive "P")
213   (let ((url (get-text-property (point) 'image-url)))
214     (cond
215      ((not url)
216       (message "No image under point"))
217      (copy-url
218       (with-temp-buffer
219         (insert url)
220         (copy-region-as-kill (point-min) (point-max))
221         (message "Copied %s" url)))
222      (t
223       (message "Browsing %s..." url)
224       (browse-url url)))))
225
226 (defun shr-insert-image ()
227   "Insert the image under point into the buffer."
228   (interactive)
229   (let ((url (get-text-property (point) 'image-url)))
230     (if (not url)
231         (message "No image under point")
232       (message "Inserting %s..." url)
233       (url-retrieve url 'shr-image-fetched
234                     (list (current-buffer) (1- (point)) (point-marker))
235                     t t))))
236
237 ;;; Utility functions.
238
239 (defun shr-transform-dom (dom)
240   (let ((result (list (pop dom))))
241     (dolist (arg (pop dom))
242       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
243                   (cdr arg))
244             result))
245     (dolist (sub dom)
246       (if (stringp sub)
247           (push (cons 'text sub) result)
248         (push (shr-transform-dom sub) result)))
249     (nreverse result)))
250
251 (defun shr-descend (dom)
252   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray))
253         (style (cdr (assq :style (cdr dom))))
254         (shr-stylesheet shr-stylesheet)
255         (start (point)))
256     (when style
257       (if (string-match "color" style)
258           (setq shr-stylesheet (nconc (shr-parse-style style)
259                                       shr-stylesheet))
260         (setq style nil)))
261     (if (fboundp function)
262         (funcall function (cdr dom))
263       (shr-generic (cdr dom)))
264     ;; If style is set, then this node has set the color.
265     (when style
266       (shr-colorize-region start (point)
267                            (cdr (assq 'color shr-stylesheet))
268                            (cdr (assq 'background-color shr-stylesheet))))))
269
270 (defun shr-generic (cont)
271   (dolist (sub cont)
272     (cond
273      ((eq (car sub) 'text)
274       (shr-insert (cdr sub)))
275      ((listp (cdr sub))
276       (shr-descend sub)))))
277
278 (defmacro shr-char-breakable-p (char)
279   "Return non-nil if a line can be broken before and after CHAR."
280   `(aref fill-find-break-point-function-table ,char))
281 (defmacro shr-char-nospace-p (char)
282   "Return non-nil if no space is required before and after CHAR."
283   `(aref fill-nospace-between-words-table ,char))
284
285 ;; KINSOKU is a Japanese word meaning a rule that should not be violated.
286 ;; In Emacs, it is a term used for characters, e.g. punctuation marks,
287 ;; parentheses, and so on, that should not be placed in the beginning
288 ;; of a line or the end of a line.
289 (defmacro shr-char-kinsoku-bol-p (char)
290   "Return non-nil if a line ought not to begin with CHAR."
291   `(aref (char-category-set ,char) ?>))
292 (defmacro shr-char-kinsoku-eol-p (char)
293   "Return non-nil if a line ought not to end with CHAR."
294   `(aref (char-category-set ,char) ?<))
295 (unless (shr-char-kinsoku-bol-p (make-char 'japanese-jisx0208 33 35))
296   (load "kinsoku" nil t))
297
298 (defun shr-insert (text)
299   (when (and (eq shr-state 'image)
300              (not (string-match "\\`[ \t\n]+\\'" text)))
301     (insert "\n")
302     (setq shr-state nil))
303   (cond
304    ((eq shr-folding-mode 'none)
305     (insert text))
306    (t
307     (when (and (string-match "\\`[ \t\n]" text)
308                (not (bolp))
309                (not (eq (char-after (1- (point))) ? )))
310       (insert " "))
311     (dolist (elem (split-string text))
312       (when (and (bolp)
313                  (> shr-indentation 0))
314         (shr-indent))
315       ;; No space is needed behind a wide character categorized as
316       ;; kinsoku-bol, between characters both categorized as nospace,
317       ;; or at the beginning of a line.
318       (let (prev)
319         (when (and (> (current-column) shr-indentation)
320                    (eq (preceding-char) ? )
321                    (or (= (line-beginning-position) (1- (point)))
322                        (and (shr-char-breakable-p
323                              (setq prev (char-after (- (point) 2))))
324                             (shr-char-kinsoku-bol-p prev))
325                        (and (shr-char-nospace-p prev)
326                             (shr-char-nospace-p (aref elem 0)))))
327           (delete-char -1)))
328       ;; The shr-start is a special variable that is used to pass
329       ;; upwards the first point in the buffer where the text really
330       ;; starts.
331       (unless shr-start
332         (setq shr-start (point)))
333       (insert elem)
334       (let (found)
335         (while (and (> (current-column) shr-width)
336                     (progn
337                       (setq found (shr-find-fill-point))
338                       (not (eolp))))
339           (when (eq (preceding-char) ? )
340             (delete-char -1))
341           (insert "\n")
342           (unless found
343             (put-text-property (1- (point)) (point) 'shr-break t)
344             ;; No space is needed at the beginning of a line.
345             (when (eq (following-char) ? )
346               (delete-char 1)))
347           (when (> shr-indentation 0)
348             (shr-indent))
349           (end-of-line))
350         (insert " ")))
351     (unless (string-match "[ \t\n]\\'" text)
352       (delete-char -1)))))
353
354 (defun shr-find-fill-point ()
355   (when (> (move-to-column shr-width) shr-width)
356     (backward-char 1))
357   (let ((bp (point))
358         failed)
359     (while (not (or (setq failed (= (current-column) shr-indentation))
360                     (eq (preceding-char) ? )
361                     (eq (following-char) ? )
362                     (shr-char-breakable-p (preceding-char))
363                     (shr-char-breakable-p (following-char))
364                     (if (eq (preceding-char) ?')
365                         (not (memq (char-after (- (point) 2))
366                                    (list nil ?\n ? )))
367                       (and (shr-char-kinsoku-bol-p (preceding-char))
368                            (shr-char-breakable-p (following-char))
369                            (not (shr-char-kinsoku-bol-p (following-char)))))
370                     (shr-char-kinsoku-eol-p (following-char))))
371       (backward-char 1))
372     (if (and (not (or failed (eolp)))
373              (eq (preceding-char) ?'))
374         (while (not (or (setq failed (eolp))
375                         (eq (following-char) ? )
376                         (shr-char-breakable-p (following-char))
377                         (shr-char-kinsoku-eol-p (following-char))))
378           (forward-char 1)))
379     (if failed
380         ;; There's no breakable point, so we give it up.
381         (let (found)
382           (goto-char bp)
383           (unless shr-kinsoku-shorten
384             (while (and (setq found (re-search-forward
385                                      "\\(\\c>\\)\\| \\|\\c<\\|\\c|"
386                                      (line-end-position) 'move))
387                         (eq (preceding-char) ?')))
388             (if (and found (not (match-beginning 1)))
389                 (goto-char (match-beginning 0)))))
390       (or
391        (eolp)
392        ;; Don't put kinsoku-bol characters at the beginning of a line,
393        ;; or kinsoku-eol characters at the end of a line.
394        (cond
395         (shr-kinsoku-shorten
396          (while (and (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
397                      (shr-char-kinsoku-eol-p (preceding-char)))
398            (backward-char 1))
399          (when (setq failed (= (current-column) shr-indentation))
400            ;; There's no breakable point that doesn't violate kinsoku,
401            ;; so we look for the second best position.
402            (while (and (progn
403                          (forward-char 1)
404                          (<= (current-column) shr-width))
405                        (progn
406                          (setq bp (point))
407                          (shr-char-kinsoku-eol-p (following-char)))))
408            (goto-char bp)))
409         ((shr-char-kinsoku-eol-p (preceding-char))
410          (if (shr-char-kinsoku-eol-p (following-char))
411              ;; There are consecutive kinsoku-eol characters.
412              (setq failed t)
413            (let ((count 4))
414              (while
415                  (progn
416                    (backward-char 1)
417                    (and (> (setq count (1- count)) 0)
418                         (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
419                         (or (shr-char-kinsoku-eol-p (preceding-char))
420                             (shr-char-kinsoku-bol-p (following-char)))))))
421            (if (setq failed (= (current-column) shr-indentation))
422                ;; There's no breakable point that doesn't violate kinsoku,
423                ;; so we go to the second best position.
424                (if (looking-at "\\(\\c<+\\)\\c<")
425                    (goto-char (match-end 1))
426                  (forward-char 1)))))
427         (t
428          (if (shr-char-kinsoku-bol-p (preceding-char))
429              ;; There are consecutive kinsoku-bol characters.
430              (setq failed t)
431            (let ((count 4))
432              (while (and (>= (setq count (1- count)) 0)
433                          (shr-char-kinsoku-bol-p (following-char))
434                          (shr-char-breakable-p (following-char)))
435                (forward-char 1))))))
436        (when (eq (following-char) ? )
437          (forward-char 1))))
438     (not failed)))
439
440 (defun shr-expand-url (url)
441   (cond
442    ;; Absolute URL.
443    ((or (not url)
444         (string-match "\\`[a-z]*:" url)
445         (not shr-base))
446     url)
447    ((and (not (string-match "/\\'" shr-base))
448          (not (string-match "\\`/" url)))
449     (concat shr-base "/" url))
450    (t
451     (concat shr-base url))))
452
453 (defun shr-ensure-newline ()
454   (unless (zerop (current-column))
455     (insert "\n")))
456
457 (defun shr-ensure-paragraph ()
458   (unless (bobp)
459     (if (<= (current-column) shr-indentation)
460         (unless (save-excursion
461                   (forward-line -1)
462                   (looking-at " *$"))
463           (insert "\n"))
464       (if (save-excursion
465             (beginning-of-line)
466             (looking-at " *$"))
467           (insert "\n")
468         (insert "\n\n")))))
469
470 (defun shr-indent ()
471   (when (> shr-indentation 0)
472     (insert (make-string shr-indentation ? ))))
473
474 (defun shr-fontize-cont (cont &rest types)
475   (let (shr-start)
476     (shr-generic cont)
477     (dolist (type types)
478       (shr-add-font (or shr-start (point)) (point) type))))
479
480 ;; Add an overlay in the region, but avoid putting the font properties
481 ;; on blank text at the start of the line, and the newline at the end,
482 ;; to avoid ugliness.
483 (defun shr-add-font (start end type)
484   (save-excursion
485     (goto-char start)
486     (while (< (point) end)
487       (when (bolp)
488         (skip-chars-forward " "))
489       (let ((overlay (make-overlay (point) (min (line-end-position) end))))
490         (overlay-put overlay 'face type))
491       (if (< (line-end-position) end)
492           (forward-line 1)
493         (goto-char end)))))
494
495 (defun shr-browse-url ()
496   "Browse the URL under point."
497   (interactive)
498   (let ((url (get-text-property (point) 'shr-url)))
499     (cond
500      ((not url)
501       (message "No link under point"))
502      ((string-match "^mailto:" url)
503       (browse-url-mail url))
504      (t
505       (browse-url url)))))
506
507 (defun shr-save-contents (directory)
508   "Save the contents from URL in a file."
509   (interactive "DSave contents of URL to directory: ")
510   (let ((url (get-text-property (point) 'shr-url)))
511     (if (not url)
512         (message "No link under point")
513       (url-retrieve (shr-encode-url url)
514                     'shr-store-contents (list url directory)
515                     nil t))))
516
517 (defun shr-store-contents (status url directory)
518   (unless (plist-get status :error)
519     (when (or (search-forward "\n\n" nil t)
520               (search-forward "\r\n\r\n" nil t))
521       (write-region (point) (point-max)
522                     (expand-file-name (file-name-nondirectory url)
523                                       directory)))))
524
525 (defun shr-image-fetched (status buffer start end)
526   (when (and (buffer-name buffer)
527              (not (plist-get status :error)))
528     (url-store-in-cache (current-buffer))
529     (when (or (search-forward "\n\n" nil t)
530               (search-forward "\r\n\r\n" nil t))
531       (let ((data (buffer-substring (point) (point-max))))
532         (with-current-buffer buffer
533           (save-excursion
534             (let ((alt (buffer-substring start end))
535                   (inhibit-read-only t))
536               (delete-region start end)
537               (goto-char start)
538               (funcall shr-put-image-function data alt)))))))
539   (kill-buffer (current-buffer)))
540
541 (defun shr-put-image (data alt)
542   "Put image DATA with a string ALT.  Return image."
543   (if (display-graphic-p)
544       (let ((image (ignore-errors
545                      (shr-rescale-image data))))
546         (when image
547           ;; When inserting big-ish pictures, put them at the
548           ;; beginning of the line.
549           (when (and (> (current-column) 0)
550                      (> (car (image-size image t)) 400))
551             (insert "\n"))
552           (insert-image image (or alt "*"))
553           (when (image-animated-p image)
554             (image-animate image nil 60)))
555         image)
556     (insert alt)))
557
558 (defun shr-rescale-image (data)
559   (let ((image (create-image data nil t :ascent 100)))
560     (if (or (not (fboundp 'imagemagick-types))
561             (not (get-buffer-window (current-buffer))))
562         image
563       (let* ((size (image-size image t))
564              (width (car size))
565              (height (cdr size))
566              (edges (window-inside-pixel-edges
567                      (get-buffer-window (current-buffer))))
568              (window-width (truncate (* shr-max-image-proportion
569                                         (- (nth 2 edges) (nth 0 edges)))))
570              (window-height (truncate (* shr-max-image-proportion
571                                          (- (nth 3 edges) (nth 1 edges)))))
572              scaled-image)
573         (when (> height window-height)
574           (setq image (or (create-image data 'imagemagick t
575                                         :height window-height
576                                         :ascent 100)
577                           image))
578           (setq size (image-size image t)))
579         (when (> (car size) window-width)
580           (setq image (or
581                        (create-image data 'imagemagick t
582                                      :width window-width
583                                      :ascent 100)
584                        image)))
585         image))))
586
587 ;; url-cache-extract autoloads url-cache.
588 (declare-function url-cache-create-filename "url-cache" (url))
589 (autoload 'mm-disable-multibyte "mm-util")
590 (autoload 'browse-url-mail "browse-url")
591
592 (defun shr-get-image-data (url)
593   "Get image data for URL.
594 Return a string with image data."
595   (with-temp-buffer
596     (mm-disable-multibyte)
597     (when (ignore-errors
598             (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
599             t)
600       (when (or (search-forward "\n\n" nil t)
601                 (search-forward "\r\n\r\n" nil t))
602         (buffer-substring (point) (point-max))))))
603
604 (defun shr-image-displayer (content-function)
605   "Return a function to display an image.
606 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
607 is an argument.  The function to be returned takes three arguments URL,
608 START, and END.  Note that START and END should be markers."
609   `(lambda (url start end)
610      (when url
611        (if (string-match "\\`cid:" url)
612            ,(when content-function
613               `(let ((image (funcall ,content-function
614                                      (substring url (match-end 0)))))
615                  (when image
616                    (goto-char start)
617                    (funcall shr-put-image-function
618                             image (buffer-substring start end))
619                    (delete-region (point) end))))
620          (url-retrieve url 'shr-image-fetched
621                        (list (current-buffer) start end)
622                        t t)))))
623
624 (defun shr-heading (cont &rest types)
625   (shr-ensure-paragraph)
626   (apply #'shr-fontize-cont cont types)
627   (shr-ensure-paragraph))
628
629 (autoload 'widget-convert-button "wid-edit")
630
631 (defun shr-urlify (start url &optional title)
632   (widget-convert-button
633    'url-link start (point)
634    :help-echo (if title (format "%s (%s)" url title) url)
635    :keymap shr-map
636    url)
637   (shr-add-font start (point) 'shr-link)
638   (put-text-property start (point) 'shr-url url))
639
640 (defun shr-encode-url (url)
641   "Encode URL."
642   (browse-url-url-encode-chars url "[)$ ]"))
643
644 (autoload 'shr-color-visible "shr-color")
645 (autoload 'shr-color->hexadecimal "shr-color")
646
647 (defun shr-color-check (fg bg)
648   "Check that FG is visible on BG.
649 Returns (fg bg) with corrected values.
650 Returns nil if the colors that would be used are the default
651 ones, in case fg and bg are nil."
652   (when (or fg bg)
653     (let ((fixed (cond ((null fg) 'fg)
654                        ((null bg) 'bg))))
655       ;; Convert colors to hexadecimal, or set them to default.
656       (let ((fg (or (shr-color->hexadecimal fg)
657                     (frame-parameter nil 'foreground-color)))
658             (bg (or (shr-color->hexadecimal bg)
659                     (frame-parameter nil 'background-color))))
660         (cond ((eq fixed 'bg)
661                ;; Only return the new fg
662                (list nil (cadr (shr-color-visible bg fg t))))
663               ((eq fixed 'fg)
664                ;; Invert args and results and return only the new bg
665                (list (cadr (shr-color-visible fg bg t)) nil))
666               (t
667                (shr-color-visible bg fg)))))))
668
669 (defun shr-colorize-region (start end fg &optional bg)
670   (when (or fg bg)
671     (let ((new-colors (shr-color-check fg bg)))
672       (when new-colors
673         (when fg
674           (shr-put-color start end :foreground (cadr new-colors)))
675         (when bg
676           (shr-put-color start end :background (car new-colors))))
677       new-colors)))
678
679 ;; Put a color in the region, but avoid putting colors on blank
680 ;; text at the start of the line, and the newline at the end, to avoid
681 ;; ugliness.  Also, don't overwrite any existing color information,
682 ;; since this can be called recursively, and we want the "inner" color
683 ;; to win.
684 (defun shr-put-color (start end type color)
685   (save-excursion
686     (goto-char start)
687     (while (< (point) end)
688       (when (and (bolp)
689                  (not (eq type :background)))
690         (skip-chars-forward " "))
691       (when (> (line-end-position) (point))
692         (shr-put-color-1 (point) (min (line-end-position) end) type color))
693       (if (< (line-end-position) end)
694           (forward-line 1)
695         (goto-char end)))
696     (when (and (eq type :background)
697                (= shr-table-depth 0))
698       (shr-expand-newlines start end color))))
699
700 (defun shr-expand-newlines (start end color)
701   (save-restriction
702     ;; Skip past all white space at the start and ends.
703     (goto-char start)
704     (skip-chars-forward " \t\n")
705     (beginning-of-line)
706     (setq start (point))
707     (goto-char end)
708     (skip-chars-backward " \t\n")
709     (forward-line 1)
710     (setq end (point))
711     (narrow-to-region start end)
712     (let ((width (shr-natural-width))
713           column)
714       (goto-char (point-min))
715       (while (not (eobp))
716         (end-of-line)
717         (when (and (< (setq column (current-column)) width)
718                    (< (setq column (shr-previous-newline-padding-width column))
719                       width))
720           (let ((overlay (make-overlay (point) (1+ (point)))))
721             (overlay-put overlay 'before-string
722                          (concat
723                           (mapconcat
724                            (lambda (overlay)
725                              (let ((string (plist-get
726                                             (overlay-properties overlay)
727                                             'before-string)))
728                                (if (not string)
729                                    ""
730                                  (overlay-put overlay 'before-string "")
731                                  string)))
732                            (overlays-at (point))
733                            "")
734                           (propertize (make-string (- width column) ? )
735                                       'face (list :background color))))))
736         (forward-line 1)))))
737
738 (defun shr-previous-newline-padding-width (width)
739   (let ((overlays (overlays-at (point)))
740         (previous-width 0))
741     (if (null overlays)
742         width
743       (dolist (overlay overlays)
744         (setq previous-width
745               (+ previous-width
746                  (length (plist-get (overlay-properties overlay)
747                                     'before-string)))))
748       (+ width previous-width))))
749
750 (defun shr-put-color-1 (start end type color)
751   (let* ((old-props (get-text-property start 'face))
752          (do-put (and (listp old-props)
753                       (not (memq type old-props))))
754          change)
755     (while (< start end)
756       (setq change (next-single-property-change start 'face nil end))
757       (when do-put
758         (put-text-property start change 'face
759                            (nconc (list type color) old-props)))
760       (setq old-props (get-text-property change 'face))
761       (setq do-put (and (listp old-props)
762                         (not (memq type old-props))))
763       (setq start change))
764     (when (and do-put
765                (> end start))
766       (put-text-property start end 'face
767                          (nconc (list type color old-props))))))
768
769 ;;; Tag-specific rendering rules.
770
771 (defun shr-tag-body (cont)
772   (let* ((start (point))
773          (fgcolor (cdr (or (assq :fgcolor cont)
774                            (assq :text cont))))
775          (bgcolor (cdr (assq :bgcolor cont)))
776          (shr-stylesheet (list (cons 'color fgcolor)
777                                (cons 'background-color bgcolor))))
778     (shr-generic cont)
779     (shr-colorize-region start (point) fgcolor bgcolor)))
780
781 (defun shr-tag-style (cont)
782   )
783
784 (defun shr-tag-script (cont)
785   )
786
787 (defun shr-tag-comment (cont)
788   )
789
790 (defun shr-tag-sup (cont)
791   (let ((start (point)))
792     (shr-generic cont)
793     (put-text-property start (point) 'display '(raise 0.5))))
794
795 (defun shr-tag-sub (cont)
796   (let ((start (point)))
797     (shr-generic cont)
798     (put-text-property start (point) 'display '(raise -0.5))))
799
800 (defun shr-tag-label (cont)
801   (shr-generic cont)
802   (shr-ensure-paragraph))
803
804 (defun shr-tag-p (cont)
805   (shr-ensure-paragraph)
806   (shr-indent)
807   (shr-generic cont)
808   (shr-ensure-paragraph))
809
810 (defun shr-tag-div (cont)
811   (shr-ensure-newline)
812   (shr-indent)
813   (shr-generic cont)
814   (shr-ensure-newline))
815
816 (defun shr-tag-s (cont)
817   (shr-fontize-cont cont 'shr-strike-through))
818
819 (defun shr-tag-del (cont)
820   (shr-fontize-cont cont 'shr-strike-through))
821
822 (defun shr-tag-b (cont)
823   (shr-fontize-cont cont 'bold))
824
825 (defun shr-tag-i (cont)
826   (shr-fontize-cont cont 'italic))
827
828 (defun shr-tag-em (cont)
829   (shr-fontize-cont cont 'bold))
830
831 (defun shr-tag-strong (cont)
832   (shr-fontize-cont cont 'bold))
833
834 (defun shr-tag-u (cont)
835   (shr-fontize-cont cont 'underline))
836
837 (defun shr-parse-style (style)
838   (when style
839     (save-match-data
840       (when (string-match "\n" style)
841         (setq style (replace-match " " t t style))))
842     (let ((plist nil))
843       (dolist (elem (split-string style ";"))
844         (when elem
845           (setq elem (split-string elem ":"))
846           (when (and (car elem)
847                      (cadr elem))
848             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
849                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
850               (when (string-match " *!important\\'" value)
851                 (setq value (substring value 0 (match-beginning 0))))
852               (push (cons (intern name obarray)
853                           value)
854                     plist)))))
855       plist)))
856
857 (defun shr-tag-base (cont)
858   (setq shr-base (cdr (assq :href cont))))
859
860 (defun shr-tag-a (cont)
861   (let ((url (cdr (assq :href cont)))
862         (title (cdr (assq :title cont)))
863         (start (point))
864         shr-start)
865     (shr-generic cont)
866     (shr-urlify (or shr-start start) (shr-expand-url url) title)))
867
868 (defun shr-tag-object (cont)
869   (let ((start (point))
870         url)
871     (dolist (elem cont)
872       (when (eq (car elem) 'embed)
873         (setq url (or url (cdr (assq :src (cdr elem))))))
874       (when (and (eq (car elem) 'param)
875                  (equal (cdr (assq :name (cdr elem))) "movie"))
876         (setq url (or url (cdr (assq :value (cdr elem)))))))
877     (when url
878       (shr-insert " [multimedia] ")
879       (shr-urlify start (shr-expand-url url)))
880     (shr-generic cont)))
881
882 (defun shr-tag-video (cont)
883   (let ((image (cdr (assq :poster cont)))
884         (url (cdr (assq :src cont)))
885         (start (point)))
886     (shr-tag-img nil image)
887     (shr-urlify start (shr-expand-url url))))
888
889 (defun shr-tag-img (cont &optional url)
890   (when (or url
891             (and cont
892                  (cdr (assq :src cont))))
893     (when (and (> (current-column) 0)
894                (not (eq shr-state 'image)))
895       (insert "\n"))
896     (let ((alt (cdr (assq :alt cont)))
897           (url (shr-expand-url (or url (cdr (assq :src cont))))))
898       (let ((start (point-marker)))
899         (when (zerop (length alt))
900           (setq alt "*"))
901         (cond
902          ((or (member (cdr (assq :height cont)) '("0" "1"))
903               (member (cdr (assq :width cont)) '("0" "1")))
904           ;; Ignore zero-sized or single-pixel images.
905           )
906          ((and (not shr-inhibit-images)
907                (string-match "\\`cid:" url))
908           (let ((url (substring url (match-end 0)))
909                 image)
910             (if (or (not shr-content-function)
911                     (not (setq image (funcall shr-content-function url))))
912                 (insert alt)
913               (funcall shr-put-image-function image alt))))
914          ((or shr-inhibit-images
915               (and shr-blocked-images
916                    (string-match shr-blocked-images url)))
917           (setq shr-start (point))
918           (let ((shr-state 'space))
919             (if (> (string-width alt) 8)
920                 (shr-insert (truncate-string-to-width alt 8))
921               (shr-insert alt))))
922          ((and (not shr-ignore-cache)
923                (url-is-cached (shr-encode-url url)))
924           (funcall shr-put-image-function (shr-get-image-data url) alt))
925          (t
926           (insert alt " ")
927           (when (and shr-ignore-cache
928                      (url-is-cached (shr-encode-url url)))
929             (let ((file (url-cache-create-filename (shr-encode-url url))))
930               (when (file-exists-p file)
931                 (delete-file file))))
932           (url-queue-retrieve
933            (shr-encode-url url) 'shr-image-fetched
934            (list (current-buffer) start (set-marker (make-marker) (1- (point))))
935            t 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