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