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