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