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