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