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