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