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