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