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