Make <li> rendering more compact
[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   (when (zerop (length url))
517     (setq url nil))
518   (cond ((or (not url)
519              (not base)
520              (string-match "\\`[a-z]*:" url))
521          ;; Absolute URL.
522          (or url (car base)))
523         ((eq (aref url 0) ?/)
524          (if (and (> (length url) 1)
525                   (eq (aref url 1) ?/))
526              ;; //host...; just use the protocol
527              (concat (nth 2 base) ":" url)
528            ;; Just use the host name part.
529            (concat (car base) url)))
530         (t
531          ;; Totally relative.
532          (concat (car base) (cadr base) url))))
533
534 (defun shr-ensure-newline ()
535   (unless (zerop (current-column))
536     (insert "\n")))
537
538 (defun shr-ensure-paragraph ()
539   (unless (bobp)
540     (if (<= (current-column) shr-indentation)
541         (unless (save-excursion
542                   (forward-line -1)
543                   (looking-at " *$"))
544           (insert "\n"))
545       (if (save-excursion
546             (beginning-of-line)
547             (looking-at " *$"))
548           (delete-region (match-beginning 0) (match-end 0))
549         (insert "\n\n")))))
550
551 (defun shr-indent ()
552   (when (> shr-indentation 0)
553     (insert (make-string shr-indentation ? ))))
554
555 (defun shr-fontize-cont (cont &rest types)
556   (let (shr-start)
557     (shr-generic cont)
558     (dolist (type types)
559       (shr-add-font (or shr-start (point)) (point) type))))
560
561 (defun shr-make-overlay (beg end &optional buffer front-advance rear-advance)
562   (let ((overlay (make-overlay beg end buffer front-advance rear-advance)))
563     (overlay-put overlay 'evaporate t)
564     overlay))
565
566 ;; Add an overlay in the region, but avoid putting the font properties
567 ;; on blank text at the start of the line, and the newline at the end,
568 ;; to avoid ugliness.
569 (defun shr-add-font (start end type)
570   (save-excursion
571     (goto-char start)
572     (while (< (point) end)
573       (when (bolp)
574         (skip-chars-forward " "))
575       (let ((overlay (shr-make-overlay (point) (min (line-end-position) end))))
576         (overlay-put overlay 'face type))
577       (if (< (line-end-position) end)
578           (forward-line 1)
579         (goto-char end)))))
580
581 (defun shr-browse-url ()
582   "Browse the URL under point."
583   (interactive)
584   (let ((url (get-text-property (point) 'shr-url)))
585     (cond
586      ((not url)
587       (message "No link under point"))
588      ((string-match "^mailto:" url)
589       (browse-url-mail url))
590      (t
591       (browse-url url)))))
592
593 (defun shr-save-contents (directory)
594   "Save the contents from URL in a file."
595   (interactive "DSave contents of URL to directory: ")
596   (let ((url (get-text-property (point) 'shr-url)))
597     (if (not url)
598         (message "No link under point")
599       (url-retrieve (shr-encode-url url)
600                     'shr-store-contents (list url directory)
601                     nil t))))
602
603 (defun shr-store-contents (status url directory)
604   (unless (plist-get status :error)
605     (when (or (search-forward "\n\n" nil t)
606               (search-forward "\r\n\r\n" nil t))
607       (write-region (point) (point-max)
608                     (expand-file-name (file-name-nondirectory url)
609                                       directory)))))
610
611 (defun shr-image-fetched (status buffer start end &optional flags)
612   (let ((image-buffer (current-buffer)))
613     (when (and (buffer-name buffer)
614                (not (plist-get status :error)))
615       (url-store-in-cache image-buffer)
616       (when (or (search-forward "\n\n" nil t)
617                 (search-forward "\r\n\r\n" nil t))
618         (let ((data (buffer-substring (point) (point-max))))
619           (with-current-buffer buffer
620             (save-excursion
621               (let ((alt (buffer-substring start end))
622                     (properties (text-properties-at start))
623                     (inhibit-read-only t))
624                 (delete-region start end)
625                 (goto-char start)
626                 (funcall shr-put-image-function data alt flags)
627                 (while properties
628                   (let ((type (pop properties))
629                         (value (pop properties)))
630                     (unless (memq type '(display image-size))
631                       (put-text-property start (point) type value))))))))))
632     (kill-buffer image-buffer)))
633
634 (defun shr-image-from-data (data)
635   "Return an image from the data: URI content DATA."
636   (when (string-match
637          "\\(\\([^/;,]+\\(/[^;,]+\\)?\\)\\(;[^;,]+\\)*\\)?,\\(.*\\)"
638          data)
639     (let ((param (match-string 4 data))
640           (payload (url-unhex-string (match-string 5 data))))
641       (when (string-match "^.*\\(;[ \t]*base64\\)$" param)
642         (setq payload (base64-decode-string payload)))
643       payload)))
644
645 (defun shr-put-image (data alt &optional flags)
646   "Put image DATA with a string ALT.  Return image."
647   (if (display-graphic-p)
648       (let* ((size (cdr (assq 'size flags)))
649              (start (point))
650              (image (cond
651                      ((eq size 'original)
652                       (create-image data nil t :ascent 100))
653                      ((eq size 'full)
654                       (ignore-errors
655                         (shr-rescale-image data t)))
656                      (t
657                       (ignore-errors
658                         (shr-rescale-image data))))))
659         (when image
660           ;; When inserting big-ish pictures, put them at the
661           ;; beginning of the line.
662           (when (and (> (current-column) 0)
663                      (> (car (image-size image t)) 400))
664             (insert "\n"))
665           (if (eq size 'original)
666               (let ((overlays (overlays-at (point))))
667                 (insert-sliced-image image (or alt "*") nil 20 1)
668                 (dolist (overlay overlays)
669                   (overlay-put overlay 'face 'default)))
670             (insert-image image (or alt "*")))
671           (put-text-property start (point) 'image-size size)
672           (when (cond ((fboundp 'image-multi-frame-p)
673                        ;; Only animate multi-frame things that specify a
674                        ;; delay; eg animated gifs as opposed to
675                        ;; multi-page tiffs.  FIXME?
676                        (cdr (image-multi-frame-p image)))
677                       ((fboundp 'image-animated-p)
678                        (image-animated-p image)))
679             (image-animate image nil 60)))
680         image)
681     (insert alt)))
682
683 (defun shr-rescale-image (data &optional force)
684   "Rescale DATA, if too big, to fit the current buffer.
685 If FORCE, rescale the image anyway."
686   (let ((image (create-image data nil t :ascent 100)))
687     (if (or (not (fboundp 'imagemagick-types))
688             (not (get-buffer-window (current-buffer))))
689         image
690       (let* ((size (image-size image t))
691              (width (car size))
692              (height (cdr size))
693              (edges (window-inside-pixel-edges
694                      (get-buffer-window (current-buffer))))
695              (window-width (truncate (* shr-max-image-proportion
696                                         (- (nth 2 edges) (nth 0 edges)))))
697              (window-height (truncate (* shr-max-image-proportion
698                                          (- (nth 3 edges) (nth 1 edges)))))
699              scaled-image)
700         (when (or force
701                   (> height window-height))
702           (setq image (or (create-image data 'imagemagick t
703                                         :height window-height
704                                         :ascent 100)
705                           image))
706           (setq size (image-size image t)))
707         (when (> (car size) window-width)
708           (setq image (or
709                        (create-image data 'imagemagick t
710                                      :width window-width
711                                      :ascent 100)
712                        image)))
713         image))))
714
715 ;; url-cache-extract autoloads url-cache.
716 (declare-function url-cache-create-filename "url-cache" (url))
717 (autoload 'mm-disable-multibyte "mm-util")
718 (autoload 'browse-url-mail "browse-url")
719
720 (defun shr-get-image-data (url)
721   "Get image data for URL.
722 Return a string with image data."
723   (with-temp-buffer
724     (mm-disable-multibyte)
725     (when (ignore-errors
726             (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
727             t)
728       (when (or (search-forward "\n\n" nil t)
729                 (search-forward "\r\n\r\n" nil t))
730         (buffer-substring (point) (point-max))))))
731
732 (defun shr-image-displayer (content-function)
733   "Return a function to display an image.
734 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
735 is an argument.  The function to be returned takes three arguments URL,
736 START, and END.  Note that START and END should be markers."
737   `(lambda (url start end)
738      (when url
739        (if (string-match "\\`cid:" url)
740            ,(when content-function
741               `(let ((image (funcall ,content-function
742                                      (substring url (match-end 0)))))
743                  (when image
744                    (goto-char start)
745                    (funcall shr-put-image-function
746                             image (buffer-substring start end))
747                    (delete-region (point) end))))
748          (url-retrieve url 'shr-image-fetched
749                        (list (current-buffer) start end)
750                        t t)))))
751
752 (defun shr-heading (cont &rest types)
753   (shr-ensure-paragraph)
754   (apply #'shr-fontize-cont cont types)
755   (shr-ensure-paragraph))
756
757 (autoload 'widget-convert-button "wid-edit")
758
759 (defun shr-urlify (start url &optional title)
760   (widget-convert-button
761    'url-link start (point)
762    :help-echo (if title (format "%s (%s)" url title) url)
763    :keymap shr-map
764    url)
765   (shr-add-font start (point) 'shr-link)
766   (put-text-property start (point) 'shr-url url))
767
768 (defun shr-encode-url (url)
769   "Encode URL."
770   (browse-url-url-encode-chars url "[)$ ]"))
771
772 (autoload 'shr-color-visible "shr-color")
773 (autoload 'shr-color->hexadecimal "shr-color")
774
775 (defun shr-color-check (fg bg)
776   "Check that FG is visible on BG.
777 Returns (fg bg) with corrected values.
778 Returns nil if the colors that would be used are the default
779 ones, in case fg and bg are nil."
780   (when (or fg bg)
781     (let ((fixed (cond ((null fg) 'fg)
782                        ((null bg) 'bg))))
783       ;; Convert colors to hexadecimal, or set them to default.
784       (let ((fg (or (shr-color->hexadecimal fg)
785                     (frame-parameter nil 'foreground-color)))
786             (bg (or (shr-color->hexadecimal bg)
787                     (frame-parameter nil 'background-color))))
788         (cond ((eq fixed 'bg)
789                ;; Only return the new fg
790                (list nil (cadr (shr-color-visible bg fg t))))
791               ((eq fixed 'fg)
792                ;; Invert args and results and return only the new bg
793                (list (cadr (shr-color-visible fg bg t)) nil))
794               (t
795                (shr-color-visible bg fg)))))))
796
797 (defun shr-colorize-region (start end fg &optional bg)
798   (when (or fg bg)
799     (let ((new-colors (shr-color-check fg bg)))
800       (when new-colors
801         (when fg
802           (shr-put-color start end :foreground (cadr new-colors)))
803         (when bg
804           (shr-put-color start end :background (car new-colors))))
805       new-colors)))
806
807 ;; Put a color in the region, but avoid putting colors on blank
808 ;; text at the start of the line, and the newline at the end, to avoid
809 ;; ugliness.  Also, don't overwrite any existing color information,
810 ;; since this can be called recursively, and we want the "inner" color
811 ;; to win.
812 (defun shr-put-color (start end type color)
813   (save-excursion
814     (goto-char start)
815     (while (< (point) end)
816       (when (and (bolp)
817                  (not (eq type :background)))
818         (skip-chars-forward " "))
819       (when (> (line-end-position) (point))
820         (shr-put-color-1 (point) (min (line-end-position) end) type color))
821       (if (< (line-end-position) end)
822           (forward-line 1)
823         (goto-char end)))
824     (when (and (eq type :background)
825                (= shr-table-depth 0))
826       (shr-expand-newlines start end color))))
827
828 (defun shr-expand-newlines (start end color)
829   (save-restriction
830     ;; Skip past all white space at the start and ends.
831     (goto-char start)
832     (skip-chars-forward " \t\n")
833     (beginning-of-line)
834     (setq start (point))
835     (goto-char end)
836     (skip-chars-backward " \t\n")
837     (forward-line 1)
838     (setq end (point))
839     (narrow-to-region start end)
840     (let ((width (shr-buffer-width))
841           column)
842       (goto-char (point-min))
843       (while (not (eobp))
844         (end-of-line)
845         (when (and (< (setq column (current-column)) width)
846                    (< (setq column (shr-previous-newline-padding-width column))
847                       width))
848           (let ((overlay (shr-make-overlay (point) (1+ (point)))))
849             (overlay-put overlay 'before-string
850                          (concat
851                           (mapconcat
852                            (lambda (overlay)
853                              (let ((string (plist-get
854                                             (overlay-properties overlay)
855                                             'before-string)))
856                                (if (not string)
857                                    ""
858                                  (overlay-put overlay 'before-string "")
859                                  string)))
860                            (overlays-at (point))
861                            "")
862                           (propertize (make-string (- width column) ? )
863                                       'face (list :background color))))))
864         (forward-line 1)))))
865
866 (defun shr-previous-newline-padding-width (width)
867   (let ((overlays (overlays-at (point)))
868         (previous-width 0))
869     (if (null overlays)
870         width
871       (dolist (overlay overlays)
872         (setq previous-width
873               (+ previous-width
874                  (length (plist-get (overlay-properties overlay)
875                                     'before-string)))))
876       (+ width previous-width))))
877
878 (defun shr-put-color-1 (start end type color)
879   (let* ((old-props (get-text-property start 'face))
880          (do-put (and (listp old-props)
881                       (not (memq type old-props))))
882          change)
883     (while (< start end)
884       (setq change (next-single-property-change start 'face nil end))
885       (when do-put
886         (put-text-property start change 'face
887                            (nconc (list type color) old-props)))
888       (setq old-props (get-text-property change 'face))
889       (setq do-put (and (listp old-props)
890                         (not (memq type old-props))))
891       (setq start change))
892     (when (and do-put
893                (> end start))
894       (put-text-property start end 'face
895                          (nconc (list type color old-props))))))
896
897 ;;; Tag-specific rendering rules.
898
899 (defun shr-tag-body (cont)
900   (let* ((start (point))
901          (fgcolor (cdr (or (assq :fgcolor cont)
902                            (assq :text cont))))
903          (bgcolor (cdr (assq :bgcolor cont)))
904          (shr-stylesheet (list (cons 'color fgcolor)
905                                (cons 'background-color bgcolor))))
906     (shr-generic cont)
907     (shr-colorize-region start (point) fgcolor bgcolor)))
908
909 (defun shr-tag-style (cont)
910   )
911
912 (defun shr-tag-script (cont)
913   )
914
915 (defun shr-tag-comment (cont)
916   )
917
918 (defun shr-dom-to-xml (dom)
919   "Convert DOM into a string containing the xml representation."
920   (let ((arg " ")
921         (text ""))
922     (dolist (sub (cdr dom))
923       (cond
924        ((listp (cdr sub))
925         (setq text (concat text (shr-dom-to-xml sub))))
926        ((eq (car sub) 'text)
927         (setq text (concat text (cdr sub))))
928        (t
929         (setq arg (concat arg (format "%s=\"%s\" "
930                                       (substring (symbol-name (car sub)) 1)
931                                       (cdr sub)))))))
932     (format "<%s%s>%s</%s>"
933             (car dom)
934             (substring arg 0 (1- (length arg)))
935             text
936             (car dom))))
937
938 (defun shr-tag-svg (cont)
939   (when (image-type-available-p 'svg)
940     (funcall shr-put-image-function
941              (shr-dom-to-xml (cons 'svg cont))
942              "SVG Image")))
943
944 (defun shr-tag-sup (cont)
945   (let ((start (point)))
946     (shr-generic cont)
947     (put-text-property start (point) 'display '(raise 0.5))))
948
949 (defun shr-tag-sub (cont)
950   (let ((start (point)))
951     (shr-generic cont)
952     (put-text-property start (point) 'display '(raise -0.5))))
953
954 (defun shr-tag-label (cont)
955   (shr-generic cont)
956   (shr-ensure-paragraph))
957
958 (defun shr-tag-p (cont)
959   (shr-ensure-paragraph)
960   (shr-indent)
961   (shr-generic cont)
962   (shr-ensure-paragraph))
963
964 (defun shr-tag-div (cont)
965   (shr-ensure-newline)
966   (shr-indent)
967   (shr-generic cont)
968   (shr-ensure-newline))
969
970 (defun shr-tag-s (cont)
971   (shr-fontize-cont cont 'shr-strike-through))
972
973 (defun shr-tag-del (cont)
974   (shr-fontize-cont cont 'shr-strike-through))
975
976 (defun shr-tag-b (cont)
977   (shr-fontize-cont cont 'bold))
978
979 (defun shr-tag-i (cont)
980   (shr-fontize-cont cont 'italic))
981
982 (defun shr-tag-em (cont)
983   (shr-fontize-cont cont 'italic))
984
985 (defun shr-tag-strong (cont)
986   (shr-fontize-cont cont 'bold))
987
988 (defun shr-tag-u (cont)
989   (shr-fontize-cont cont 'underline))
990
991 (defun shr-parse-style (style)
992   (when style
993     (save-match-data
994       (when (string-match "\n" style)
995         (setq style (replace-match " " t t style))))
996     (let ((plist nil))
997       (dolist (elem (split-string style ";"))
998         (when elem
999           (setq elem (split-string elem ":"))
1000           (when (and (car elem)
1001                      (cadr elem))
1002             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
1003                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
1004               (when (string-match " *!important\\'" value)
1005                 (setq value (substring value 0 (match-beginning 0))))
1006               (push (cons (intern name obarray)
1007                           value)
1008                     plist)))))
1009       plist)))
1010
1011 (defun shr-tag-base (cont)
1012   (setq shr-base (shr-parse-base (cdr (assq :href cont))))
1013   (shr-generic cont))
1014
1015 (defun shr-tag-a (cont)
1016   (let ((url (cdr (assq :href cont)))
1017         (title (cdr (assq :title cont)))
1018         (start (point))
1019         shr-start)
1020     (shr-generic cont)
1021     (when url
1022       (shr-urlify (or shr-start start) (shr-expand-url url) title))))
1023
1024 (defun shr-tag-object (cont)
1025   (let ((start (point))
1026         url)
1027     (dolist (elem cont)
1028       (when (eq (car elem) 'embed)
1029         (setq url (or url (cdr (assq :src (cdr elem))))))
1030       (when (and (eq (car elem) 'param)
1031                  (equal (cdr (assq :name (cdr elem))) "movie"))
1032         (setq url (or url (cdr (assq :value (cdr elem)))))))
1033     (when url
1034       (shr-insert " [multimedia] ")
1035       (shr-urlify start (shr-expand-url url)))
1036     (shr-generic cont)))
1037
1038 (defun shr-tag-video (cont)
1039   (let ((image (cdr (assq :poster cont)))
1040         (url (cdr (assq :src cont)))
1041         (start (point)))
1042     (shr-tag-img nil image)
1043     (shr-urlify start (shr-expand-url url))))
1044
1045 (defun shr-tag-img (cont &optional url)
1046   (when (or url
1047             (and cont
1048                  (cdr (assq :src cont))))
1049     (when (and (> (current-column) 0)
1050                (not (eq shr-state 'image)))
1051       (insert "\n"))
1052     (let ((alt (cdr (assq :alt cont)))
1053           (url (shr-expand-url (or url (cdr (assq :src cont))))))
1054       (let ((start (point-marker)))
1055         (when (zerop (length alt))
1056           (setq alt "*"))
1057         (cond
1058          ((or (member (cdr (assq :height cont)) '("0" "1"))
1059               (member (cdr (assq :width cont)) '("0" "1")))
1060           ;; Ignore zero-sized or single-pixel images.
1061           )
1062          ((and (not shr-inhibit-images)
1063                (string-match "\\`data:" url))
1064           (let ((image (shr-image-from-data (substring url (match-end 0)))))
1065             (if image
1066                 (funcall shr-put-image-function image alt)
1067               (insert alt))))
1068          ((and (not shr-inhibit-images)
1069                (string-match "\\`cid:" url))
1070           (let ((url (substring url (match-end 0)))
1071                 image)
1072             (if (or (not shr-content-function)
1073                     (not (setq image (funcall shr-content-function url))))
1074                 (insert alt)
1075               (funcall shr-put-image-function image alt))))
1076          ((or shr-inhibit-images
1077               (and shr-blocked-images
1078                    (string-match shr-blocked-images url)))
1079           (setq shr-start (point))
1080           (let ((shr-state 'space))
1081             (if (> (string-width alt) 8)
1082                 (shr-insert (truncate-string-to-width alt 8))
1083               (shr-insert alt))))
1084          ((and (not shr-ignore-cache)
1085                (url-is-cached (shr-encode-url url)))
1086           (funcall shr-put-image-function (shr-get-image-data url) alt))
1087          (t
1088           (insert alt " ")
1089           (when (and shr-ignore-cache
1090                      (url-is-cached (shr-encode-url url)))
1091             (let ((file (url-cache-create-filename (shr-encode-url url))))
1092               (when (file-exists-p file)
1093                 (delete-file file))))
1094           (url-queue-retrieve
1095            (shr-encode-url url) 'shr-image-fetched
1096            (list (current-buffer) start (set-marker (make-marker) (1- (point))))
1097            t t)))
1098         (when (zerop shr-table-depth) ;; We are not in a table.
1099           (put-text-property start (point) 'keymap shr-map)
1100           (put-text-property start (point) 'shr-alt alt)
1101           (put-text-property start (point) 'image-url url)
1102           (put-text-property start (point) 'image-displayer
1103                              (shr-image-displayer shr-content-function))
1104           (put-text-property start (point) 'help-echo alt))
1105         (setq shr-state 'image)))))
1106
1107 (defun shr-tag-pre (cont)
1108   (let ((shr-folding-mode 'none))
1109     (shr-ensure-newline)
1110     (shr-indent)
1111     (shr-generic cont)
1112     (shr-ensure-newline)))
1113
1114 (defun shr-tag-blockquote (cont)
1115   (shr-ensure-paragraph)
1116   (shr-indent)
1117   (let ((shr-indentation (+ shr-indentation 4)))
1118     (shr-generic cont))
1119   (shr-ensure-paragraph))
1120
1121 (defun shr-tag-ul (cont)
1122   (shr-ensure-paragraph)
1123   (let ((shr-list-mode 'ul))
1124     (shr-generic cont))
1125   (shr-ensure-paragraph))
1126
1127 (defun shr-tag-ol (cont)
1128   (shr-ensure-paragraph)
1129   (let ((shr-list-mode 1))
1130     (shr-generic cont))
1131   (shr-ensure-paragraph))
1132
1133 (defun shr-tag-li (cont)
1134   (shr-ensure-newline)
1135   (shr-indent)
1136   (let* ((bullet
1137           (if (numberp shr-list-mode)
1138               (prog1
1139                   (format "%d " shr-list-mode)
1140                 (setq shr-list-mode (1+ shr-list-mode)))
1141             shr-bullet))
1142          (shr-indentation (+ shr-indentation (length bullet))))
1143     (insert bullet)
1144     (shr-generic cont)))
1145
1146 (defun shr-tag-br (cont)
1147   (when (and (not (bobp))
1148              ;; Only add a newline if we break the current line, or
1149              ;; the previous line isn't a blank line.
1150              (or (not (bolp))
1151                  (and (> (- (point) 2) (point-min))
1152                       (not (= (char-after (- (point) 2)) ?\n)))))
1153     (insert "\n")
1154     (shr-indent))
1155   (shr-generic cont))
1156
1157 (defun shr-tag-span (cont)
1158   (let ((title (cdr (assq :title cont))))
1159     (shr-generic cont)
1160     (when title
1161       (when shr-start
1162         (let ((overlay (shr-make-overlay shr-start (point))))
1163           (overlay-put overlay 'help-echo title))))))
1164
1165 (defun shr-tag-h1 (cont)
1166   (shr-heading cont 'bold 'underline))
1167
1168 (defun shr-tag-h2 (cont)
1169   (shr-heading cont 'bold))
1170
1171 (defun shr-tag-h3 (cont)
1172   (shr-heading cont 'italic))
1173
1174 (defun shr-tag-h4 (cont)
1175   (shr-heading cont))
1176
1177 (defun shr-tag-h5 (cont)
1178   (shr-heading cont))
1179
1180 (defun shr-tag-h6 (cont)
1181   (shr-heading cont))
1182
1183 (defun shr-tag-hr (cont)
1184   (shr-ensure-newline)
1185   (insert (make-string shr-width shr-hr-line) "\n"))
1186
1187 (defun shr-tag-title (cont)
1188   (shr-heading cont 'bold 'underline))
1189
1190 (defun shr-tag-font (cont)
1191   (let* ((start (point))
1192          (color (cdr (assq :color cont)))
1193          (shr-stylesheet (nconc (list (cons 'color color))
1194                                 shr-stylesheet)))
1195     (shr-generic cont)
1196     (when color
1197       (shr-colorize-region start (point) color
1198                            (cdr (assq 'background-color shr-stylesheet))))))
1199
1200 ;;; Table rendering algorithm.
1201
1202 ;; Table rendering is the only complicated thing here.  We do this by
1203 ;; first counting how many TDs there are in each TR, and registering
1204 ;; how wide they think they should be ("width=45%", etc).  Then we
1205 ;; render each TD separately (this is done in temporary buffers, so
1206 ;; that we can use all the rendering machinery as if we were in the
1207 ;; main buffer).  Now we know how much space each TD really takes, so
1208 ;; we then render everything again with the new widths, and finally
1209 ;; insert all these boxes into the main buffer.
1210 (defun shr-tag-table-1 (cont)
1211   (setq cont (or (cdr (assq 'tbody cont))
1212                  cont))
1213   (let* ((shr-inhibit-images t)
1214          (shr-table-depth (1+ shr-table-depth))
1215          (shr-kinsoku-shorten t)
1216          ;; Find all suggested widths.
1217          (columns (shr-column-specs cont))
1218          ;; Compute how many characters wide each TD should be.
1219          (suggested-widths (shr-pro-rate-columns columns))
1220          ;; Do a "test rendering" to see how big each TD is (this can
1221          ;; be smaller (if there's little text) or bigger (if there's
1222          ;; unbreakable text).
1223          (sketch (shr-make-table cont suggested-widths))
1224          ;; Compute the "natural" width by setting each column to 500
1225          ;; characters and see how wide they really render.
1226          (natural (shr-make-table cont (make-vector (length columns) 500)))
1227          (sketch-widths (shr-table-widths sketch natural suggested-widths)))
1228     ;; This probably won't work very well.
1229     (when (> (+ (loop for width across sketch-widths
1230                       summing (1+ width))
1231                 shr-indentation 1)
1232              (frame-width))
1233       (setq truncate-lines t))
1234     ;; Then render the table again with these new "hard" widths.
1235     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
1236   ;; Finally, insert all the images after the table.  The Emacs buffer
1237   ;; model isn't strong enough to allow us to put the images actually
1238   ;; into the tables.
1239   (when (zerop shr-table-depth)
1240     (dolist (elem (shr-find-elements cont 'img))
1241       (shr-tag-img (cdr elem)))))
1242
1243 (defun shr-tag-table (cont)
1244   (shr-ensure-paragraph)
1245   (let* ((caption (cdr (assq 'caption cont)))
1246          (header (cdr (assq 'thead cont)))
1247          (body (or (cdr (assq 'tbody cont)) cont))
1248          (footer (cdr (assq 'tfoot cont)))
1249          (bgcolor (cdr (assq :bgcolor cont)))
1250          (start (point))
1251          (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1252                                 shr-stylesheet))
1253          (nheader (if header (shr-max-columns header)))
1254          (nbody (if body (shr-max-columns body)))
1255          (nfooter (if footer (shr-max-columns footer))))
1256     (if (and (not caption)
1257              (not header)
1258              (not (cdr (assq 'tbody cont)))
1259              (not (cdr (assq 'tr cont)))
1260              (not footer))
1261         ;; The table is totally invalid and just contains random junk.
1262         ;; Try to output it anyway.
1263         (shr-generic cont)
1264       ;; It's a real table, so render it.
1265       (shr-tag-table-1
1266        (nconc
1267         (if caption `((tr (td ,@caption))))
1268         (if header
1269             (if footer
1270                 ;; hader + body + footer
1271                 (if (= nheader nbody)
1272                     (if (= nbody nfooter)
1273                         `((tr (td (table (tbody ,@header ,@body ,@footer)))))
1274                       (nconc `((tr (td (table (tbody ,@header ,@body)))))
1275                              (if (= nfooter 1)
1276                                  footer
1277                                `((tr (td (table (tbody ,@footer))))))))
1278                   (nconc `((tr (td (table (tbody ,@header)))))
1279                          (if (= nbody nfooter)
1280                              `((tr (td (table (tbody ,@body ,@footer)))))
1281                            (nconc `((tr (td (table (tbody ,@body)))))
1282                                   (if (= nfooter 1)
1283                                       footer
1284                                     `((tr (td (table (tbody ,@footer))))))))))
1285               ;; header + body
1286               (if (= nheader nbody)
1287                   `((tr (td (table (tbody ,@header ,@body)))))
1288                 (if (= nheader 1)
1289                     `(,@header (tr (td (table (tbody ,@body)))))
1290                   `((tr (td (table (tbody ,@header))))
1291                     (tr (td (table (tbody ,@body))))))))
1292           (if footer
1293               ;; body + footer
1294               (if (= nbody nfooter)
1295                   `((tr (td (table (tbody ,@body ,@footer)))))
1296                 (nconc `((tr (td (table (tbody ,@body)))))
1297                        (if (= nfooter 1)
1298                            footer
1299                          `((tr (td (table (tbody ,@footer))))))))
1300             (if caption
1301                 `((tr (td (table (tbody ,@body)))))
1302               body))))))
1303     (when bgcolor
1304       (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1305                            bgcolor))))
1306
1307 (defun shr-find-elements (cont type)
1308   (let (result)
1309     (dolist (elem cont)
1310       (cond ((eq (car elem) type)
1311              (push elem result))
1312             ((consp (cdr elem))
1313              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
1314     (nreverse result)))
1315
1316 (defun shr-insert-table (table widths)
1317   (shr-insert-table-ruler widths)
1318   (dolist (row table)
1319     (let ((start (point))
1320           (height (let ((max 0))
1321                     (dolist (column row)
1322                       (setq max (max max (cadr column))))
1323                     max)))
1324       (dotimes (i height)
1325         (shr-indent)
1326         (insert shr-table-vertical-line "\n"))
1327       (dolist (column row)
1328         (goto-char start)
1329         (let ((lines (nth 2 column))
1330               (overlay-lines (nth 3 column))
1331               overlay overlay-line)
1332           (dolist (line lines)
1333             (setq overlay-line (pop overlay-lines))
1334             (end-of-line)
1335             (insert line shr-table-vertical-line)
1336             (dolist (overlay overlay-line)
1337               (let ((o (shr-make-overlay (- (point) (nth 0 overlay) 1)
1338                                          (- (point) (nth 1 overlay) 1)))
1339                     (properties (nth 2 overlay)))
1340                 (while properties
1341                   (overlay-put o (pop properties) (pop properties)))))
1342             (forward-line 1))
1343           ;; Add blank lines at padding at the bottom of the TD,
1344           ;; possibly.
1345           (dotimes (i (- height (length lines)))
1346             (end-of-line)
1347             (let ((start (point)))
1348               (insert (make-string (string-width (car lines)) ? )
1349                       shr-table-vertical-line)
1350               (when (nth 4 column)
1351                 (shr-put-color start (1- (point)) :background (nth 4 column))))
1352             (forward-line 1)))))
1353     (shr-insert-table-ruler widths)))
1354
1355 (defun shr-insert-table-ruler (widths)
1356   (when (and (bolp)
1357              (> shr-indentation 0))
1358     (shr-indent))
1359   (insert shr-table-corner)
1360   (dotimes (i (length widths))
1361     (insert (make-string (aref widths i) shr-table-horizontal-line)
1362             shr-table-corner))
1363   (insert "\n"))
1364
1365 (defun shr-table-widths (table natural-table suggested-widths)
1366   (let* ((length (length suggested-widths))
1367          (widths (make-vector length 0))
1368          (natural-widths (make-vector length 0)))
1369     (dolist (row table)
1370       (let ((i 0))
1371         (dolist (column row)
1372           (aset widths i (max (aref widths i) column))
1373           (setq i (1+ i)))))
1374     (dolist (row natural-table)
1375       (let ((i 0))
1376         (dolist (column row)
1377           (aset natural-widths i (max (aref natural-widths i) column))
1378           (setq i (1+ i)))))
1379     (let ((extra (- (apply '+ (append suggested-widths nil))
1380                     (apply '+ (append widths nil))))
1381           (expanded-columns 0))
1382       ;; We have extra, unused space, so divide this space amongst the
1383       ;; columns.
1384       (when (> extra 0)
1385         ;; If the natural width is wider than the rendered width, we
1386         ;; want to allow the column to expand.
1387         (dotimes (i length)
1388           (when (> (aref natural-widths i) (aref widths i))
1389             (setq expanded-columns (1+ expanded-columns))))
1390         (dotimes (i length)
1391           (when (> (aref natural-widths i) (aref widths i))
1392             (aset widths i (min
1393                             (aref natural-widths i)
1394                             (+ (/ extra expanded-columns)
1395                                (aref widths i))))))))
1396     widths))
1397
1398 (defun shr-make-table (cont widths &optional fill)
1399   (let ((trs nil))
1400     (dolist (row cont)
1401       (when (eq (car row) 'tr)
1402         (let ((tds nil)
1403               (columns (cdr row))
1404               (i 0)
1405               column)
1406           (while (< i (length widths))
1407             (setq column (pop columns))
1408             (when (or (memq (car column) '(td th))
1409                       (null column))
1410               (push (shr-render-td (cdr column) (aref widths i) fill)
1411                     tds)
1412               (setq i (1+ i))))
1413           (push (nreverse tds) trs))))
1414     (nreverse trs)))
1415
1416 (defun shr-render-td (cont width fill)
1417   (with-temp-buffer
1418     (let ((bgcolor (cdr (assq :bgcolor cont)))
1419           (fgcolor (cdr (assq :fgcolor cont)))
1420           (style (cdr (assq :style cont)))
1421           (shr-stylesheet shr-stylesheet)
1422           overlays actual-colors)
1423       (when style
1424         (setq style (and (string-match "color" style)
1425                          (shr-parse-style style))))
1426       (when bgcolor
1427         (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1428       (when fgcolor
1429         (setq style (nconc (list (cons 'color fgcolor)) style)))
1430       (when style
1431         (setq shr-stylesheet (append style shr-stylesheet)))
1432       (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
1433         (if cache
1434             (progn
1435               (insert (car cache))
1436               (let ((end (length (car cache))))
1437                 (dolist (overlay (cadr cache))
1438                   (let ((new-overlay
1439                          (shr-make-overlay (1+ (- end (nth 0 overlay)))
1440                                            (1+ (- end (nth 1 overlay)))))
1441                         (properties (nth 2 overlay)))
1442                     (while properties
1443                       (overlay-put new-overlay
1444                                    (pop properties) (pop properties)))))))
1445           (let ((shr-width width)
1446                 (shr-indentation 0))
1447             (shr-descend (cons 'td cont)))
1448           ;; Delete padding at the bottom of the TDs.
1449           (delete-region
1450            (point)
1451            (progn
1452              (skip-chars-backward " \t\n")
1453              (end-of-line)
1454              (point)))
1455           (push (list (cons width cont) (buffer-string)
1456                       (shr-overlays-in-region (point-min) (point-max)))
1457                 shr-content-cache)))
1458       (goto-char (point-min))
1459       (let ((max 0))
1460         (while (not (eobp))
1461           (end-of-line)
1462           (setq max (max max (current-column)))
1463           (forward-line 1))
1464         (when fill
1465           (goto-char (point-min))
1466           ;; If the buffer is totally empty, then put a single blank
1467           ;; line here.
1468           (if (zerop (buffer-size))
1469               (insert (make-string width ? ))
1470             ;; Otherwise, fill the buffer.
1471             (while (not (eobp))
1472               (end-of-line)
1473               (when (> (- width (current-column)) 0)
1474                 (insert (make-string (- width (current-column)) ? )))
1475               (forward-line 1)))
1476           (when style
1477             (setq actual-colors
1478                   (shr-colorize-region
1479                    (point-min) (point-max)
1480                    (cdr (assq 'color shr-stylesheet))
1481                    (cdr (assq 'background-color shr-stylesheet))))))
1482         (if fill
1483             (list max
1484                   (count-lines (point-min) (point-max))
1485                   (split-string (buffer-string) "\n")
1486                   (shr-collect-overlays)
1487                   (car actual-colors))
1488           max)))))
1489
1490 (defun shr-buffer-width ()
1491   (goto-char (point-min))
1492   (let ((max 0))
1493     (while (not (eobp))
1494       (end-of-line)
1495       (setq max (max max (current-column)))
1496       (forward-line 1))
1497     max))
1498
1499 (defun shr-collect-overlays ()
1500   (save-excursion
1501     (goto-char (point-min))
1502     (let ((overlays nil))
1503       (while (not (eobp))
1504         (push (shr-overlays-in-region (point) (line-end-position))
1505               overlays)
1506         (forward-line 1))
1507       (nreverse overlays))))
1508
1509 (defun shr-overlays-in-region (start end)
1510   (let (result)
1511     (dolist (overlay (overlays-in start end))
1512       (push (list (if (> start (overlay-start overlay))
1513                       (- end start)
1514                     (- end (overlay-start overlay)))
1515                   (if (< end (overlay-end overlay))
1516                       0
1517                     (- end (overlay-end overlay)))
1518                   (overlay-properties overlay))
1519             result))
1520     (nreverse result)))
1521
1522 (defun shr-pro-rate-columns (columns)
1523   (let ((total-percentage 0)
1524         (widths (make-vector (length columns) 0)))
1525     (dotimes (i (length columns))
1526       (setq total-percentage (+ total-percentage (aref columns i))))
1527     (setq total-percentage (/ 1.0 total-percentage))
1528     (dotimes (i (length columns))
1529       (aset widths i (max (truncate (* (aref columns i)
1530                                        total-percentage
1531                                        (- shr-width (1+ (length columns)))))
1532                           10)))
1533     widths))
1534
1535 ;; Return a summary of the number and shape of the TDs in the table.
1536 (defun shr-column-specs (cont)
1537   (let ((columns (make-vector (shr-max-columns cont) 1)))
1538     (dolist (row cont)
1539       (when (eq (car row) 'tr)
1540         (let ((i 0))
1541           (dolist (column (cdr row))
1542             (when (memq (car column) '(td th))
1543               (let ((width (cdr (assq :width (cdr column)))))
1544                 (when (and width
1545                            (string-match "\\([0-9]+\\)%" width)
1546                            (not (zerop (setq width (string-to-number
1547                                                     (match-string 1 width))))))
1548                   (aset columns i (/ width 100.0))))
1549               (setq i (1+ i)))))))
1550     columns))
1551
1552 (defun shr-count (cont elem)
1553   (let ((i 0))
1554     (dolist (sub cont)
1555       (when (eq (car sub) elem)
1556         (setq i (1+ i))))
1557     i))
1558
1559 (defun shr-max-columns (cont)
1560   (let ((max 0))
1561     (dolist (row cont)
1562       (when (eq (car row) 'tr)
1563         (setq max (max max (+ (shr-count (cdr row) 'td)
1564                               (shr-count (cdr row) 'th))))))
1565     max))
1566
1567 (provide 'shr)
1568
1569 ;; Local Variables:
1570 ;; coding: utf-8
1571 ;; End:
1572
1573 ;;; shr.el ends here