mm-decode.el (shr-map): Silence the byte compiler
[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)
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-put-color start end :foreground (cadr new-colors)))
847         (when bg
848           (shr-put-color start end :background (car new-colors))))
849       new-colors)))
850
851 ;; Put a color in the region, but avoid putting colors on blank
852 ;; text at the start of the line, and the newline at the end, to avoid
853 ;; ugliness.  Also, don't overwrite any existing color information,
854 ;; since this can be called recursively, and we want the "inner" color
855 ;; to win.
856 (defun shr-put-color (start end type color)
857   (save-excursion
858     (goto-char start)
859     (while (< (point) end)
860       (when (and (bolp)
861                  (not (eq type :background)))
862         (skip-chars-forward " "))
863       (when (> (line-end-position) (point))
864         (shr-put-color-1 (point) (min (line-end-position) end) type color))
865       (if (< (line-end-position) end)
866           (forward-line 1)
867         (goto-char end)))
868     (when (and (eq type :background)
869                (= shr-table-depth 0))
870       (shr-expand-newlines start end color))))
871
872 (defun shr-expand-newlines (start end color)
873   (save-restriction
874     ;; Skip past all white space at the start and ends.
875     (goto-char start)
876     (skip-chars-forward " \t\n")
877     (beginning-of-line)
878     (setq start (point))
879     (goto-char end)
880     (skip-chars-backward " \t\n")
881     (forward-line 1)
882     (setq end (point))
883     (narrow-to-region start end)
884     (let ((width (shr-buffer-width))
885           column)
886       (goto-char (point-min))
887       (while (not (eobp))
888         (end-of-line)
889         (when (and (< (setq column (current-column)) width)
890                    (< (setq column (shr-previous-newline-padding-width column))
891                       width))
892           (let ((overlay (make-overlay (point) (1+ (point)))))
893             (overlay-put overlay 'before-string
894                          (concat
895                           (mapconcat
896                            (lambda (overlay)
897                              (let ((string (plist-get
898                                             (overlay-properties overlay)
899                                             'before-string)))
900                                (if (not string)
901                                    ""
902                                  (overlay-put overlay 'before-string "")
903                                  string)))
904                            (overlays-at (point))
905                            "")
906                           (propertize (make-string (- width column) ? )
907                                       'face (list :background color))))))
908         (forward-line 1)))))
909
910 (defun shr-previous-newline-padding-width (width)
911   (let ((overlays (overlays-at (point)))
912         (previous-width 0))
913     (if (null overlays)
914         width
915       (dolist (overlay overlays)
916         (setq previous-width
917               (+ previous-width
918                  (length (plist-get (overlay-properties overlay)
919                                     'before-string)))))
920       (+ width previous-width))))
921
922 (defun shr-put-color-1 (start end type color)
923   (let* ((old-props (get-text-property start 'face))
924          (do-put (and (listp old-props)
925                       (not (memq type old-props))))
926          change)
927     (while (< start end)
928       (setq change (next-single-property-change start 'face nil end))
929       (when do-put
930         (add-face-text-property start change (list type color)))
931       (setq old-props (get-text-property change 'face))
932       (setq do-put (and (listp old-props)
933                         (not (memq type old-props))))
934       (setq start change))
935     (when (and do-put
936                (> end start))
937       (put-text-property start end 'face
938                          (nconc (list type color old-props))))))
939
940 ;;; Tag-specific rendering rules.
941
942 (defun shr-tag-body (cont)
943   (let* ((start (point))
944          (fgcolor (cdr (or (assq :fgcolor cont)
945                            (assq :text cont))))
946          (bgcolor (cdr (assq :bgcolor cont)))
947          (shr-stylesheet (list (cons 'color fgcolor)
948                                (cons 'background-color bgcolor))))
949     (shr-generic cont)
950     (shr-colorize-region start (point) fgcolor bgcolor)))
951
952 (defun shr-tag-style (cont)
953   )
954
955 (defun shr-tag-script (cont)
956   )
957
958 (defun shr-tag-comment (cont)
959   )
960
961 (defun shr-dom-to-xml (dom)
962   "Convert DOM into a string containing the xml representation."
963   (let ((arg " ")
964         (text ""))
965     (dolist (sub (cdr dom))
966       (cond
967        ((listp (cdr sub))
968         (setq text (concat text (shr-dom-to-xml sub))))
969        ((eq (car sub) 'text)
970         (setq text (concat text (cdr sub))))
971        (t
972         (setq arg (concat arg (format "%s=\"%s\" "
973                                       (substring (symbol-name (car sub)) 1)
974                                       (cdr sub)))))))
975     (format "<%s%s>%s</%s>"
976             (car dom)
977             (substring arg 0 (1- (length arg)))
978             text
979             (car dom))))
980
981 (defun shr-tag-svg (cont)
982   (when (image-type-available-p 'svg)
983     (funcall shr-put-image-function
984              (shr-dom-to-xml (cons 'svg cont))
985              "SVG Image")))
986
987 (defun shr-tag-sup (cont)
988   (let ((start (point)))
989     (shr-generic cont)
990     (put-text-property start (point) 'display '(raise 0.5))))
991
992 (defun shr-tag-sub (cont)
993   (let ((start (point)))
994     (shr-generic cont)
995     (put-text-property start (point) 'display '(raise -0.5))))
996
997 (defun shr-tag-label (cont)
998   (shr-generic cont)
999   (shr-ensure-paragraph))
1000
1001 (defun shr-tag-p (cont)
1002   (shr-ensure-paragraph)
1003   (shr-indent)
1004   (shr-generic cont)
1005   (shr-ensure-paragraph))
1006
1007 (defun shr-tag-div (cont)
1008   (shr-ensure-newline)
1009   (shr-indent)
1010   (shr-generic cont)
1011   (shr-ensure-newline))
1012
1013 (defun shr-tag-s (cont)
1014   (shr-fontize-cont cont 'shr-strike-through))
1015
1016 (defun shr-tag-del (cont)
1017   (shr-fontize-cont cont 'shr-strike-through))
1018
1019 (defun shr-tag-b (cont)
1020   (shr-fontize-cont cont 'bold))
1021
1022 (defun shr-tag-i (cont)
1023   (shr-fontize-cont cont 'italic))
1024
1025 (defun shr-tag-em (cont)
1026   (shr-fontize-cont cont 'italic))
1027
1028 (defun shr-tag-strong (cont)
1029   (shr-fontize-cont cont 'bold))
1030
1031 (defun shr-tag-u (cont)
1032   (shr-fontize-cont cont 'underline))
1033
1034 (defun shr-parse-style (style)
1035   (when style
1036     (save-match-data
1037       (when (string-match "\n" style)
1038         (setq style (replace-match " " t t style))))
1039     (let ((plist nil))
1040       (dolist (elem (split-string style ";"))
1041         (when elem
1042           (setq elem (split-string elem ":"))
1043           (when (and (car elem)
1044                      (cadr elem))
1045             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
1046                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
1047               (when (string-match " *!important\\'" value)
1048                 (setq value (substring value 0 (match-beginning 0))))
1049               (push (cons (intern name obarray)
1050                           value)
1051                     plist)))))
1052       plist)))
1053
1054 (defun shr-tag-base (cont)
1055   (setq shr-base (shr-parse-base (cdr (assq :href cont))))
1056   (shr-generic cont))
1057
1058 (defun shr-tag-a (cont)
1059   (let ((url (cdr (assq :href cont)))
1060         (title (cdr (assq :title cont)))
1061         (start (point))
1062         shr-start)
1063     (shr-generic cont)
1064     (when url
1065       (shr-urlify (or shr-start start) (shr-expand-url url) title))))
1066
1067 (defun shr-tag-object (cont)
1068   (let ((start (point))
1069         url)
1070     (dolist (elem cont)
1071       (when (eq (car elem) 'embed)
1072         (setq url (or url (cdr (assq :src (cdr elem))))))
1073       (when (and (eq (car elem) 'param)
1074                  (equal (cdr (assq :name (cdr elem))) "movie"))
1075         (setq url (or url (cdr (assq :value (cdr elem)))))))
1076     (when url
1077       (shr-insert " [multimedia] ")
1078       (shr-urlify start (shr-expand-url url)))
1079     (shr-generic cont)))
1080
1081 (defun shr-tag-video (cont)
1082   (let ((image (cdr (assq :poster cont)))
1083         (url (cdr (assq :src cont)))
1084         (start (point)))
1085     (shr-tag-img nil image)
1086     (shr-urlify start (shr-expand-url url))))
1087
1088 (defun shr-tag-img (cont &optional url)
1089   (when (or url
1090             (and cont
1091                  (cdr (assq :src cont))))
1092     (when (and (> (current-column) 0)
1093                (not (eq shr-state 'image)))
1094       (insert "\n"))
1095     (let ((alt (cdr (assq :alt cont)))
1096           (url (shr-expand-url (or url (cdr (assq :src cont))))))
1097       (let ((start (point-marker)))
1098         (when (zerop (length alt))
1099           (setq alt "*"))
1100         (cond
1101          ((or (member (cdr (assq :height cont)) '("0" "1"))
1102               (member (cdr (assq :width cont)) '("0" "1")))
1103           ;; Ignore zero-sized or single-pixel images.
1104           )
1105          ((and (not shr-inhibit-images)
1106                (string-match "\\`data:" url))
1107           (let ((image (shr-image-from-data (substring url (match-end 0)))))
1108             (if image
1109                 (funcall shr-put-image-function image alt)
1110               (insert alt))))
1111          ((and (not shr-inhibit-images)
1112                (string-match "\\`cid:" url))
1113           (let ((url (substring url (match-end 0)))
1114                 image)
1115             (if (or (not shr-content-function)
1116                     (not (setq image (funcall shr-content-function url))))
1117                 (insert alt)
1118               (funcall shr-put-image-function image alt))))
1119          ((or shr-inhibit-images
1120               (and shr-blocked-images
1121                    (string-match shr-blocked-images url)))
1122           (setq shr-start (point))
1123           (let ((shr-state 'space))
1124             (if (> (string-width alt) 8)
1125                 (shr-insert (truncate-string-to-width alt 8))
1126               (shr-insert alt))))
1127          ((and (not shr-ignore-cache)
1128                (url-is-cached (shr-encode-url url)))
1129           (funcall shr-put-image-function (shr-get-image-data url) alt))
1130          (t
1131           (insert alt " ")
1132           (when (and shr-ignore-cache
1133                      (url-is-cached (shr-encode-url url)))
1134             (let ((file (url-cache-create-filename (shr-encode-url url))))
1135               (when (file-exists-p file)
1136                 (delete-file file))))
1137           (url-queue-retrieve
1138            (shr-encode-url url) 'shr-image-fetched
1139            (list (current-buffer) start (set-marker (make-marker) (1- (point))))
1140            t t)))
1141         (when (zerop shr-table-depth) ;; We are not in a table.
1142           (put-text-property start (point) 'keymap shr-map)
1143           (put-text-property start (point) 'shr-alt alt)
1144           (put-text-property start (point) 'image-url url)
1145           (put-text-property start (point) 'image-displayer
1146                              (shr-image-displayer shr-content-function))
1147           (put-text-property start (point) 'help-echo alt))
1148         (setq shr-state 'image)))))
1149
1150 (defun shr-tag-pre (cont)
1151   (let ((shr-folding-mode 'none))
1152     (shr-ensure-newline)
1153     (shr-indent)
1154     (shr-generic cont)
1155     (shr-ensure-newline)))
1156
1157 (defun shr-tag-blockquote (cont)
1158   (shr-ensure-paragraph)
1159   (shr-indent)
1160   (let ((shr-indentation (+ shr-indentation 4)))
1161     (shr-generic cont))
1162   (shr-ensure-paragraph))
1163
1164 (defun shr-tag-ul (cont)
1165   (shr-ensure-paragraph)
1166   (let ((shr-list-mode 'ul))
1167     (shr-generic cont))
1168   (shr-ensure-paragraph))
1169
1170 (defun shr-tag-ol (cont)
1171   (shr-ensure-paragraph)
1172   (let ((shr-list-mode 1))
1173     (shr-generic cont))
1174   (shr-ensure-paragraph))
1175
1176 (defun shr-tag-li (cont)
1177   (shr-ensure-newline)
1178   (shr-indent)
1179   (let* ((bullet
1180           (if (numberp shr-list-mode)
1181               (prog1
1182                   (format "%d " shr-list-mode)
1183                 (setq shr-list-mode (1+ shr-list-mode)))
1184             shr-bullet))
1185          (shr-indentation (+ shr-indentation (length bullet))))
1186     (insert bullet)
1187     (shr-generic cont)))
1188
1189 (defun shr-tag-br (cont)
1190   (when (and (not (bobp))
1191              ;; Only add a newline if we break the current line, or
1192              ;; the previous line isn't a blank line.
1193              (or (not (bolp))
1194                  (and (> (- (point) 2) (point-min))
1195                       (not (= (char-after (- (point) 2)) ?\n)))))
1196     (insert "\n")
1197     (shr-indent))
1198   (shr-generic cont))
1199
1200 (defun shr-tag-span (cont)
1201   (let ((title (cdr (assq :title cont))))
1202     (shr-generic cont)
1203     (when (and title
1204                shr-start)
1205       (put-text-property shr-start (point) 'help-echo title))))
1206
1207 (defun shr-tag-h1 (cont)
1208   (shr-heading cont 'bold 'underline))
1209
1210 (defun shr-tag-h2 (cont)
1211   (shr-heading cont 'bold))
1212
1213 (defun shr-tag-h3 (cont)
1214   (shr-heading cont 'italic))
1215
1216 (defun shr-tag-h4 (cont)
1217   (shr-heading cont))
1218
1219 (defun shr-tag-h5 (cont)
1220   (shr-heading cont))
1221
1222 (defun shr-tag-h6 (cont)
1223   (shr-heading cont))
1224
1225 (defun shr-tag-hr (cont)
1226   (shr-ensure-newline)
1227   (insert (make-string shr-width shr-hr-line) "\n"))
1228
1229 (defun shr-tag-title (cont)
1230   (shr-heading cont 'bold 'underline))
1231
1232 (defun shr-tag-font (cont)
1233   (let* ((start (point))
1234          (color (cdr (assq :color cont)))
1235          (shr-stylesheet (nconc (list (cons 'color color))
1236                                 shr-stylesheet)))
1237     (shr-generic cont)
1238     (when color
1239       (shr-colorize-region start (point) color
1240                            (cdr (assq 'background-color shr-stylesheet))))))
1241
1242 ;;; Table rendering algorithm.
1243
1244 ;; Table rendering is the only complicated thing here.  We do this by
1245 ;; first counting how many TDs there are in each TR, and registering
1246 ;; how wide they think they should be ("width=45%", etc).  Then we
1247 ;; render each TD separately (this is done in temporary buffers, so
1248 ;; that we can use all the rendering machinery as if we were in the
1249 ;; main buffer).  Now we know how much space each TD really takes, so
1250 ;; we then render everything again with the new widths, and finally
1251 ;; insert all these boxes into the main buffer.
1252 (defun shr-tag-table-1 (cont)
1253   (setq cont (or (cdr (assq 'tbody cont))
1254                  cont))
1255   (let* ((shr-inhibit-images t)
1256          (shr-table-depth (1+ shr-table-depth))
1257          (shr-kinsoku-shorten t)
1258          ;; Find all suggested widths.
1259          (columns (shr-column-specs cont))
1260          ;; Compute how many characters wide each TD should be.
1261          (suggested-widths (shr-pro-rate-columns columns))
1262          ;; Do a "test rendering" to see how big each TD is (this can
1263          ;; be smaller (if there's little text) or bigger (if there's
1264          ;; unbreakable text).
1265          (sketch (shr-make-table cont suggested-widths))
1266          ;; Compute the "natural" width by setting each column to 500
1267          ;; characters and see how wide they really render.
1268          (natural (shr-make-table cont (make-vector (length columns) 500)))
1269          (sketch-widths (shr-table-widths sketch natural suggested-widths)))
1270     ;; This probably won't work very well.
1271     (when (> (+ (loop for width across sketch-widths
1272                       summing (1+ width))
1273                 shr-indentation 1)
1274              (frame-width))
1275       (setq truncate-lines t))
1276     ;; Then render the table again with these new "hard" widths.
1277     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
1278   ;; Finally, insert all the images after the table.  The Emacs buffer
1279   ;; model isn't strong enough to allow us to put the images actually
1280   ;; into the tables.
1281   (when (zerop shr-table-depth)
1282     (dolist (elem (shr-find-elements cont 'img))
1283       (shr-tag-img (cdr elem)))))
1284
1285 (defun shr-tag-table (cont)
1286   (shr-ensure-paragraph)
1287   (let* ((caption (cdr (assq 'caption cont)))
1288          (header (cdr (assq 'thead cont)))
1289          (body (or (cdr (assq 'tbody cont)) cont))
1290          (footer (cdr (assq 'tfoot cont)))
1291          (bgcolor (cdr (assq :bgcolor cont)))
1292          (start (point))
1293          (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
1294                                 shr-stylesheet))
1295          (nheader (if header (shr-max-columns header)))
1296          (nbody (if body (shr-max-columns body)))
1297          (nfooter (if footer (shr-max-columns footer))))
1298     (if (and (not caption)
1299              (not header)
1300              (not (cdr (assq 'tbody cont)))
1301              (not (cdr (assq 'tr cont)))
1302              (not footer))
1303         ;; The table is totally invalid and just contains random junk.
1304         ;; Try to output it anyway.
1305         (shr-generic cont)
1306       ;; It's a real table, so render it.
1307       (shr-tag-table-1
1308        (nconc
1309         (if caption `((tr (td ,@caption))))
1310         (if header
1311             (if footer
1312                 ;; hader + body + footer
1313                 (if (= nheader nbody)
1314                     (if (= nbody nfooter)
1315                         `((tr (td (table (tbody ,@header ,@body ,@footer)))))
1316                       (nconc `((tr (td (table (tbody ,@header ,@body)))))
1317                              (if (= nfooter 1)
1318                                  footer
1319                                `((tr (td (table (tbody ,@footer))))))))
1320                   (nconc `((tr (td (table (tbody ,@header)))))
1321                          (if (= nbody nfooter)
1322                              `((tr (td (table (tbody ,@body ,@footer)))))
1323                            (nconc `((tr (td (table (tbody ,@body)))))
1324                                   (if (= nfooter 1)
1325                                       footer
1326                                     `((tr (td (table (tbody ,@footer))))))))))
1327               ;; header + body
1328               (if (= nheader nbody)
1329                   `((tr (td (table (tbody ,@header ,@body)))))
1330                 (if (= nheader 1)
1331                     `(,@header (tr (td (table (tbody ,@body)))))
1332                   `((tr (td (table (tbody ,@header))))
1333                     (tr (td (table (tbody ,@body))))))))
1334           (if footer
1335               ;; body + footer
1336               (if (= nbody nfooter)
1337                   `((tr (td (table (tbody ,@body ,@footer)))))
1338                 (nconc `((tr (td (table (tbody ,@body)))))
1339                        (if (= nfooter 1)
1340                            footer
1341                          `((tr (td (table (tbody ,@footer))))))))
1342             (if caption
1343                 `((tr (td (table (tbody ,@body)))))
1344               body))))))
1345     (when bgcolor
1346       (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
1347                            bgcolor))))
1348
1349 (defun shr-find-elements (cont type)
1350   (let (result)
1351     (dolist (elem cont)
1352       (cond ((eq (car elem) type)
1353              (push elem result))
1354             ((consp (cdr elem))
1355              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
1356     (nreverse result)))
1357
1358 (defun shr-insert-table (table widths)
1359   (shr-insert-table-ruler widths)
1360   (dolist (row table)
1361     (let ((start (point))
1362           (height (let ((max 0))
1363                     (dolist (column row)
1364                       (setq max (max max (cadr column))))
1365                     max)))
1366       (dotimes (i height)
1367         (shr-indent)
1368         (insert shr-table-vertical-line "\n"))
1369       (dolist (column row)
1370         (goto-char start)
1371         (let ((lines (nth 2 column)))
1372           (dolist (line lines)
1373             (end-of-line)
1374             (insert line shr-table-vertical-line)
1375             (forward-line 1))
1376           ;; Add blank lines at padding at the bottom of the TD,
1377           ;; possibly.
1378           (dotimes (i (- height (length lines)))
1379             (end-of-line)
1380             (let ((start (point)))
1381               (insert (make-string (string-width (car lines)) ? )
1382                       shr-table-vertical-line)
1383               (when (nth 4 column)
1384                 (shr-put-color start (1- (point)) :background (nth 4 column))))
1385             (forward-line 1)))))
1386     (shr-insert-table-ruler widths)))
1387
1388 (defun shr-insert-table-ruler (widths)
1389   (when (and (bolp)
1390              (> shr-indentation 0))
1391     (shr-indent))
1392   (insert shr-table-corner)
1393   (dotimes (i (length widths))
1394     (insert (make-string (aref widths i) shr-table-horizontal-line)
1395             shr-table-corner))
1396   (insert "\n"))
1397
1398 (defun shr-table-widths (table natural-table suggested-widths)
1399   (let* ((length (length suggested-widths))
1400          (widths (make-vector length 0))
1401          (natural-widths (make-vector length 0)))
1402     (dolist (row table)
1403       (let ((i 0))
1404         (dolist (column row)
1405           (aset widths i (max (aref widths i) column))
1406           (setq i (1+ i)))))
1407     (dolist (row natural-table)
1408       (let ((i 0))
1409         (dolist (column row)
1410           (aset natural-widths i (max (aref natural-widths i) column))
1411           (setq i (1+ i)))))
1412     (let ((extra (- (apply '+ (append suggested-widths nil))
1413                     (apply '+ (append widths nil))))
1414           (expanded-columns 0))
1415       ;; We have extra, unused space, so divide this space amongst the
1416       ;; columns.
1417       (when (> extra 0)
1418         ;; If the natural width is wider than the rendered width, we
1419         ;; want to allow the column to expand.
1420         (dotimes (i length)
1421           (when (> (aref natural-widths i) (aref widths i))
1422             (setq expanded-columns (1+ expanded-columns))))
1423         (dotimes (i length)
1424           (when (> (aref natural-widths i) (aref widths i))
1425             (aset widths i (min
1426                             (aref natural-widths i)
1427                             (+ (/ extra expanded-columns)
1428                                (aref widths i))))))))
1429     widths))
1430
1431 (defun shr-make-table (cont widths &optional fill)
1432   (or (cadr (assoc (list cont widths fill) shr-content-cache))
1433       (let ((data (shr-make-table-1 cont widths fill)))
1434         (push (list (list cont widths fill) data)
1435               shr-content-cache)
1436         data)))
1437
1438 (defun shr-make-table-1 (cont widths &optional fill)
1439   (let ((trs nil))
1440     (dolist (row cont)
1441       (when (eq (car row) 'tr)
1442         (let ((tds nil)
1443               (columns (cdr row))
1444               (i 0)
1445               column)
1446           (while (< i (length widths))
1447             (setq column (pop columns))
1448             (when (or (memq (car column) '(td th))
1449                       (null column))
1450               (push (shr-render-td (cdr column) (aref widths i) fill)
1451                     tds)
1452               (setq i (1+ i))))
1453           (push (nreverse tds) trs))))
1454     (nreverse trs)))
1455
1456 (defun shr-render-td (cont width fill)
1457   (with-temp-buffer
1458     (let ((bgcolor (cdr (assq :bgcolor cont)))
1459           (fgcolor (cdr (assq :fgcolor cont)))
1460           (style (cdr (assq :style cont)))
1461           (shr-stylesheet shr-stylesheet)
1462           actual-colors)
1463       (when style
1464         (setq style (and (string-match "color" style)
1465                          (shr-parse-style style))))
1466       (when bgcolor
1467         (setq style (nconc (list (cons 'background-color bgcolor)) style)))
1468       (when fgcolor
1469         (setq style (nconc (list (cons 'color fgcolor)) style)))
1470       (when style
1471         (setq shr-stylesheet (append style shr-stylesheet)))
1472       (let ((shr-width width)
1473             (shr-indentation 0))
1474         (shr-descend (cons 'td cont)))
1475       ;; Delete padding at the bottom of the TDs.
1476       (delete-region
1477        (point)
1478        (progn
1479          (skip-chars-backward " \t\n")
1480          (end-of-line)
1481          (point)))
1482       (goto-char (point-min))
1483       (let ((max 0))
1484         (while (not (eobp))
1485           (end-of-line)
1486           (setq max (max max (current-column)))
1487           (forward-line 1))
1488         (when fill
1489           (goto-char (point-min))
1490           ;; If the buffer is totally empty, then put a single blank
1491           ;; line here.
1492           (if (zerop (buffer-size))
1493               (insert (make-string width ? ))
1494             ;; Otherwise, fill the buffer.
1495             (while (not (eobp))
1496               (end-of-line)
1497               (when (> (- width (current-column)) 0)
1498                 (insert (make-string (- width (current-column)) ? )))
1499               (forward-line 1)))
1500           (when style
1501             (setq actual-colors
1502                   (shr-colorize-region
1503                    (point-min) (point-max)
1504                    (cdr (assq 'color shr-stylesheet))
1505                    (cdr (assq 'background-color shr-stylesheet))))))
1506         (if fill
1507             (list max
1508                   (count-lines (point-min) (point-max))
1509                   (split-string (buffer-string) "\n")
1510                   nil
1511                   (car actual-colors))
1512           max)))))
1513
1514 (defun shr-buffer-width ()
1515   (goto-char (point-min))
1516   (let ((max 0))
1517     (while (not (eobp))
1518       (end-of-line)
1519       (setq max (max max (current-column)))
1520       (forward-line 1))
1521     max))
1522
1523 (defun shr-pro-rate-columns (columns)
1524   (let ((total-percentage 0)
1525         (widths (make-vector (length columns) 0)))
1526     (dotimes (i (length columns))
1527       (setq total-percentage (+ total-percentage (aref columns i))))
1528     (setq total-percentage (/ 1.0 total-percentage))
1529     (dotimes (i (length columns))
1530       (aset widths i (max (truncate (* (aref columns i)
1531                                        total-percentage
1532                                        (- shr-width (1+ (length columns)))))
1533                           10)))
1534     widths))
1535
1536 ;; Return a summary of the number and shape of the TDs in the table.
1537 (defun shr-column-specs (cont)
1538   (let ((columns (make-vector (shr-max-columns cont) 1)))
1539     (dolist (row cont)
1540       (when (eq (car row) 'tr)
1541         (let ((i 0))
1542           (dolist (column (cdr row))
1543             (when (memq (car column) '(td th))
1544               (let ((width (cdr (assq :width (cdr column)))))
1545                 (when (and width
1546                            (string-match "\\([0-9]+\\)%" width)
1547                            (not (zerop (setq width (string-to-number
1548                                                     (match-string 1 width))))))
1549                   (aset columns i (/ width 100.0))))
1550               (setq i (1+ i)))))))
1551     columns))
1552
1553 (defun shr-count (cont elem)
1554   (let ((i 0))
1555     (dolist (sub cont)
1556       (when (eq (car sub) elem)
1557         (setq i (1+ i))))
1558     i))
1559
1560 (defun shr-max-columns (cont)
1561   (let ((max 0))
1562     (dolist (row cont)
1563       (when (eq (car row) 'tr)
1564         (setq max (max max (+ (shr-count (cdr row) 'td)
1565                               (shr-count (cdr row) 'th))))))
1566     max))
1567
1568 ;; Emacs less than 24.3
1569 (unless (fboundp 'add-face-text-property)
1570   (defun add-face-text-property (beg end face)
1571     "Combine FACE BEG and END."
1572     (let ((b beg))
1573       (while (< b end)
1574         (let ((oldval (get-text-property b 'face)))
1575           (put-text-property
1576            b (setq b (next-single-property-change b 'face nil end))
1577            'face (cond ((null oldval)
1578                         face)
1579                        ((and (consp oldval)
1580                              (not (keywordp (car oldval))))
1581                         (cons face oldval))
1582                        (t
1583                         (list face oldval)))))))))
1584
1585 (provide 'shr)
1586
1587 ;; Local Variables:
1588 ;; coding: utf-8
1589 ;; End:
1590
1591 ;;; shr.el ends here