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