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