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