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