0b3e1a9072a5a6213558ec1c1e30e201e375c8e1
[gnus] / lisp / shr.el
1 ;;; shr.el --- Simple HTML Renderer
2
3 ;; Copyright (C) 2010 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 (unless (aref (char-category-set (make-char 'japanese-jisx0208 33 35)) ?>)
36   (load "kinsoku" nil t))
37
38 (defgroup shr nil
39   "Simple HTML Renderer"
40   :group 'mail)
41
42 (defcustom shr-max-image-proportion 0.9
43   "How big pictures displayed are in relation to the window they're in.
44 A value of 0.7 means that they are allowed to take up 70% of the
45 width and height of the window.  If they are larger than this,
46 and Emacs supports it, then the images will be rescaled down to
47 fit these criteria."
48   :version "24.1"
49   :group 'shr
50   :type 'float)
51
52 (defcustom shr-blocked-images nil
53   "Images that have URLs matching this regexp will be blocked."
54   :version "24.1"
55   :group 'shr
56   :type 'regexp)
57
58 (defcustom shr-table-horizontal-line ?-
59   "Character used to draw horizontal table lines."
60   :group 'shr
61   :type 'character)
62
63 (defcustom shr-table-vertical-line ?|
64   "Character used to draw vertical table lines."
65   :group 'shr
66   :type 'character)
67
68 (defcustom shr-table-corner ?+
69   "Character used to draw table corners."
70   :group 'shr
71   :type 'character)
72
73 (defcustom shr-hr-line ?-
74   "Character used to draw hr lines."
75   :group 'shr
76   :type 'character)
77
78 (defcustom shr-width fill-column
79   "Frame width to use for rendering."
80   :type 'integer
81   :group 'shr)
82
83 (defvar shr-content-function nil
84   "If bound, this should be a function that will return the content.
85 This is used for cid: URLs, and the function is called with the
86 cid: URL as the argument.")
87
88 ;;; Internal variables.
89
90 (defvar shr-folding-mode nil)
91 (defvar shr-state nil)
92 (defvar shr-start nil)
93 (defvar shr-indentation 0)
94 (defvar shr-inhibit-images nil)
95 (defvar shr-list-mode nil)
96 (defvar shr-content-cache nil)
97 (defvar shr-kinsoku-shorten nil)
98 (defvar shr-table-depth 0)
99
100 (defvar shr-map
101   (let ((map (make-sparse-keymap)))
102     (define-key map "a" 'shr-show-alt-text)
103     (define-key map "i" 'shr-browse-image)
104     (define-key map "I" 'shr-insert-image)
105     (define-key map "u" 'shr-copy-url)
106     (define-key map "v" 'shr-browse-url)
107     (define-key map "o" 'shr-save-contents)
108     (define-key map "\r" 'shr-browse-url)
109     map))
110
111 ;; Public functions and commands.
112
113 ;;;###autoload
114 (defun shr-insert-document (dom)
115   (setq shr-content-cache nil)
116   (let ((shr-state nil)
117         (shr-start nil))
118     (shr-descend (shr-transform-dom dom))))
119
120 (defun shr-copy-url ()
121   "Copy the URL under point to the kill ring.
122 If called twice, then try to fetch the URL and see whether it
123 redirects somewhere else."
124   (interactive)
125   (let ((url (get-text-property (point) 'shr-url)))
126     (cond
127      ((not url)
128       (message "No URL under point"))
129      ;; Resolve redirected URLs.
130      ((equal url (car kill-ring))
131       (url-retrieve
132        url
133        (lambda (a)
134          (when (and (consp a)
135                     (eq (car a) :redirect))
136            (with-temp-buffer
137              (insert (cadr a))
138              (goto-char (point-min))
139              ;; Remove common tracking junk from the URL.
140              (when (re-search-forward ".utm_.*" nil t)
141                (replace-match "" t t))
142              (message "Copied %s" (buffer-string))
143              (copy-region-as-kill (point-min) (point-max)))))))
144      ;; Copy the URL to the kill ring.
145      (t
146       (with-temp-buffer
147         (insert url)
148         (copy-region-as-kill (point-min) (point-max))
149         (message "Copied %s" url))))))
150
151 (defun shr-show-alt-text ()
152   "Show the ALT text of the image under point."
153   (interactive)
154   (let ((text (get-text-property (point) 'shr-alt)))
155     (if (not text)
156         (message "No image under point")
157       (message "%s" text))))
158
159 (defun shr-browse-image ()
160   "Browse the image under point."
161   (interactive)
162   (let ((url (get-text-property (point) 'image-url)))
163     (if (not url)
164         (message "No image under point")
165       (message "Browsing %s..." url)
166       (browse-url url))))
167
168 (defun shr-insert-image ()
169   "Insert the image under point into the buffer."
170   (interactive)
171   (let ((url (get-text-property (point) 'image-url)))
172     (if (not url)
173         (message "No image under point")
174       (message "Inserting %s..." url)
175       (url-retrieve url 'shr-image-fetched
176                     (list (current-buffer) (1- (point)) (point-marker))
177                     t))))
178
179 ;;; Utility functions.
180
181 (defun shr-transform-dom (dom)
182   (let ((result (list (pop dom))))
183     (dolist (arg (pop dom))
184       (push (cons (intern (concat ":" (symbol-name (car arg))) obarray)
185                   (cdr arg))
186             result))
187     (dolist (sub dom)
188       (if (stringp sub)
189           (push (cons 'text sub) result)
190         (push (shr-transform-dom sub) result)))
191     (nreverse result)))
192
193 (defun shr-descend (dom)
194   (let ((function (intern (concat "shr-tag-" (symbol-name (car dom))) obarray)))
195     (if (fboundp function)
196         (funcall function (cdr dom))
197       (shr-generic (cdr dom)))))
198
199 (defun shr-generic (cont)
200   (dolist (sub cont)
201     (cond
202      ((eq (car sub) 'text)
203       (shr-insert (cdr sub)))
204      ((listp (cdr sub))
205       (shr-descend sub)))))
206
207 (defun shr-insert (text)
208   (when (and (eq shr-state 'image)
209              (not (string-match "\\`[ \t\n]+\\'" text)))
210     (insert "\n")
211     (setq shr-state nil))
212   (cond
213    ((eq shr-folding-mode 'none)
214     (insert text))
215    (t
216     (when (and (string-match "\\`[ \t\n]" text)
217                (not (bolp))
218                (not (eq (char-after (1- (point))) ? )))
219       (insert " "))
220     (dolist (elem (split-string text))
221       (when (and (bolp)
222                  (> shr-indentation 0))
223         (shr-indent))
224       ;; The shr-start is a special variable that is used to pass
225       ;; upwards the first point in the buffer where the text really
226       ;; starts.
227       (unless shr-start
228         (setq shr-start (point)))
229       ;; No space is needed behind a wide character categorized as
230       ;; kinsoku-bol, between characters both categorized as nospace,
231       ;; or at the beginning of a line.
232       (let (prev)
233         (when (and (eq (preceding-char) ? )
234                    (or (= (line-beginning-position) (1- (point)))
235                        (and (aref fill-find-break-point-function-table
236                                   (setq prev (char-after (- (point) 2))))
237                             (aref (char-category-set prev) ?>))
238                        (and (aref fill-nospace-between-words-table prev)
239                             (aref fill-nospace-between-words-table
240                                   (aref elem 0)))))
241           (delete-char -1)))
242       (insert elem)
243       (let (found)
244         (while (and (> (current-column) shr-width)
245                     (progn
246                       (setq found (shr-find-fill-point))
247                       (not (eolp))))
248           (when (eq (preceding-char) ? )
249             (delete-char -1))
250           (insert "\n")
251           (unless found
252             (put-text-property (1- (point)) (point) 'shr-break t)
253             ;; No space is needed at the beginning of a line.
254             (when (eq (following-char) ? )
255               (delete-char 1)))
256           (when (> shr-indentation 0)
257             (shr-indent))
258           (end-of-line))
259         (insert " ")))
260     (unless (string-match "[ \t\n]\\'" text)
261       (delete-char -1)))))
262
263 (defun shr-find-fill-point ()
264   (when (> (move-to-column shr-width) shr-width)
265     (backward-char 1))
266   (let (failed)
267     (while (not
268             (or (setq failed (= (current-column) shr-indentation))
269                 (eq (preceding-char) ? )
270                 (eq (following-char) ? )
271                 (aref fill-find-break-point-function-table (preceding-char))))
272       (backward-char 1))
273     (if failed
274         ;; There's no breakable point, so we give it up.
275         (progn
276           (end-of-line)
277           (while (aref fill-find-break-point-function-table (preceding-char))
278             (backward-char 1))
279           nil)
280       (or (eolp)
281           ;; Don't put kinsoku-bol characters at the beginning of a line,
282           ;; or kinsoku-eol characters at the end of a line,
283           (let ((count 4))
284             (if (or shr-kinsoku-shorten
285                     (and (aref (char-category-set (preceding-char)) ?<)
286                          (progn
287                            (setq count (1- count))
288                            (backward-char 1)
289                            t)))
290                 (while (and
291                         (>= (setq count (1- count)) 0)
292                         (not (memq (preceding-char) (list ?\C-@ ?\n ? )))
293                         (or (aref (char-category-set (preceding-char)) ?<)
294                             (aref (char-category-set (following-char)) ?>)))
295                   (backward-char 1))
296               (while (and (>= (setq count (1- count)) 0)
297                           (aref (char-category-set (following-char)) ?>)
298                           (aref fill-find-break-point-function-table
299                                 (following-char)))
300                 (forward-char 1)))
301             (when (eq (following-char) ? )
302               (forward-char 1))
303             t)))))
304
305 (defun shr-ensure-newline ()
306   (unless (zerop (current-column))
307     (insert "\n")))
308
309 (defun shr-ensure-paragraph ()
310   (unless (bobp)
311     (if (<= (current-column) shr-indentation)
312         (unless (save-excursion
313                   (forward-line -1)
314                   (looking-at " *$"))
315           (insert "\n"))
316       (if (save-excursion
317             (beginning-of-line)
318             (looking-at " *$"))
319           (insert "\n")
320         (insert "\n\n")))))
321
322 (defun shr-indent ()
323   (when (> shr-indentation 0)
324     (insert (make-string shr-indentation ? ))))
325
326 (defun shr-fontize-cont (cont &rest types)
327   (let (shr-start)
328     (shr-generic cont)
329     (dolist (type types)
330       (shr-add-font (or shr-start (point)) (point) type))))
331
332 ;; Add an overlay in the region, but avoid putting the font properties
333 ;; on blank text at the start of the line, and the newline at the end,
334 ;; to avoid ugliness.
335 (defun shr-add-font (start end type)
336   (save-excursion
337     (goto-char start)
338     (while (< (point) end)
339       (when (bolp)
340         (skip-chars-forward " "))
341       (let ((overlay (make-overlay (point) (min (line-end-position) end))))
342         (overlay-put overlay 'face type))
343       (if (< (line-end-position) end)
344           (forward-line 1)
345         (goto-char end)))))
346
347 (defun shr-browse-url ()
348   "Browse the URL under point."
349   (interactive)
350   (let ((url (get-text-property (point) 'shr-url)))
351     (cond
352      ((not url)
353       (message "No link under point"))
354      ((string-match "^mailto:" url)
355       (browse-url-mailto url))
356      (t
357       (browse-url url)))))
358
359 (defun shr-save-contents (directory)
360   "Save the contents from URL in a file."
361   (interactive "DSave contents of URL to directory: ")
362   (let ((url (get-text-property (point) 'shr-url)))
363     (if (not url)
364         (message "No link under point")
365       (url-retrieve (shr-encode-url url)
366                     'shr-store-contents (list url directory)))))
367
368 (defun shr-store-contents (status url directory)
369   (unless (plist-get status :error)
370     (when (or (search-forward "\n\n" nil t)
371               (search-forward "\r\n\r\n" nil t))
372       (write-region (point) (point-max)
373                     (expand-file-name (file-name-nondirectory url)
374                                       directory)))))
375
376 (defun shr-image-fetched (status buffer start end)
377   (when (and (buffer-name buffer)
378              (not (plist-get status :error)))
379     (url-store-in-cache (current-buffer))
380     (when (or (search-forward "\n\n" nil t)
381               (search-forward "\r\n\r\n" nil t))
382       (let ((data (buffer-substring (point) (point-max))))
383         (with-current-buffer buffer
384           (let ((alt (buffer-substring start end))
385                 (inhibit-read-only t))
386             (delete-region start end)
387             (goto-char start)
388             (shr-put-image data alt))))))
389   (kill-buffer (current-buffer)))
390
391 (defun shr-put-image (data alt)
392   (if (display-graphic-p)
393       (let ((image (ignore-errors
394                      (shr-rescale-image data))))
395         (when image
396           ;; When inserting big-ish pictures, put them at the
397           ;; beginning of the line.
398           (when (and (> (current-column) 0)
399                      (> (car (image-size image t)) 400))
400             (insert "\n"))
401           (insert-image image (or alt "*"))))
402     (insert alt)))
403
404 (defun shr-rescale-image (data)
405   (if (or (not (fboundp 'imagemagick-types))
406           (not (get-buffer-window (current-buffer))))
407       (create-image data nil t)
408     (let* ((image (create-image data nil t))
409            (size (image-size image t))
410            (width (car size))
411            (height (cdr size))
412            (edges (window-inside-pixel-edges
413                    (get-buffer-window (current-buffer))))
414            (window-width (truncate (* shr-max-image-proportion
415                                       (- (nth 2 edges) (nth 0 edges)))))
416            (window-height (truncate (* shr-max-image-proportion
417                                        (- (nth 3 edges) (nth 1 edges)))))
418            scaled-image)
419       (when (> height window-height)
420         (setq image (or (create-image data 'imagemagick t
421                                       :height window-height)
422                         image))
423         (setq size (image-size image t)))
424       (when (> (car size) window-width)
425         (setq image (or
426                      (create-image data 'imagemagick t
427                                    :width window-width)
428                      image)))
429       image)))
430
431 ;; url-cache-extract autoloads url-cache.
432 (declare-function url-cache-create-filename "url-cache" (url))
433 (autoload 'mm-disable-multibyte "mm-util")
434 (autoload 'browse-url-mailto "browse-url")
435
436 (defun shr-get-image-data (url)
437   "Get image data for URL.
438 Return a string with image data."
439   (with-temp-buffer
440     (mm-disable-multibyte)
441     (when (ignore-errors
442             (url-cache-extract (url-cache-create-filename (shr-encode-url url)))
443             t)
444       (when (or (search-forward "\n\n" nil t)
445                 (search-forward "\r\n\r\n" nil t))
446         (buffer-substring (point) (point-max))))))
447
448 (defun shr-image-displayer (content-function)
449   "Return a function to display an image.
450 CONTENT-FUNCTION is a function to retrieve an image for a cid url that
451 is an argument.  The function to be returned takes three arguments URL,
452 START, and END."
453   `(lambda (url start end)
454      (when url
455        (if (string-match "\\`cid:" url)
456            ,(when content-function
457               `(let ((image (funcall ,content-function
458                                      (substring url (match-end 0)))))
459                  (when image
460                    (goto-char start)
461                    (shr-put-image image
462                                   (prog1
463                                       (buffer-substring-no-properties start end)
464                                     (delete-region start end))))))
465          (url-retrieve url 'shr-image-fetched
466                        (list (current-buffer) start end)
467                        t)))))
468
469 (defun shr-heading (cont &rest types)
470   (shr-ensure-paragraph)
471   (apply #'shr-fontize-cont cont types)
472   (shr-ensure-paragraph))
473
474 (autoload 'widget-convert-button "wid-edit")
475
476 (defun shr-urlify (start url)
477   (widget-convert-button
478    'url-link start (point)
479    :help-echo url
480    :keymap shr-map
481    url)
482   (put-text-property start (point) 'shr-url url))
483
484 (defun shr-encode-url (url)
485   "Encode URL."
486   (browse-url-url-encode-chars url "[)$ ]"))
487
488 ;;; Tag-specific rendering rules.
489
490 (defun shr-tag-p (cont)
491   (shr-ensure-paragraph)
492   (shr-indent)
493   (shr-generic cont)
494   (shr-ensure-paragraph))
495
496 (defun shr-tag-div (cont)
497   (shr-ensure-newline)
498   (shr-indent)
499   (shr-generic cont)
500   (shr-ensure-newline))
501
502 (defun shr-tag-b (cont)
503   (shr-fontize-cont cont 'bold))
504
505 (defun shr-tag-i (cont)
506   (shr-fontize-cont cont 'italic))
507
508 (defun shr-tag-em (cont)
509   (shr-fontize-cont cont 'bold))
510
511 (defun shr-tag-strong (cont)
512   (shr-fontize-cont cont 'bold))
513
514 (defun shr-tag-u (cont)
515   (shr-fontize-cont cont 'underline))
516
517 (defun shr-tag-s (cont)
518   (shr-fontize-cont cont 'strike-through))
519
520 (defun shr-tag-span (cont)
521   (let ((start (point))
522         (color (cdr (assq 'color (shr-parse-style (cdr (assq :style cont)))))))
523     (shr-generic cont)
524     (when color
525       (let ((overlay (make-overlay start (point))))
526         (overlay-put overlay 'face (cons 'foreground-color color))))))
527
528 (defun shr-tag-font (cont)
529   (let ((start (point))
530         (color (cdr (assq :color cont))))
531     (shr-generic cont)
532     (when color
533       (let ((overlay (make-overlay start (point))))
534         (overlay-put overlay 'face (cons 'foreground-color color))))))
535
536 (defun shr-parse-style (style)
537   (when style
538     (let ((plist nil))
539       (dolist (elem (split-string style ";"))
540         (when elem
541           (setq elem (split-string elem ":"))
542           (when (and (car elem)
543                      (cadr elem))
544             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
545                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
546               (push (cons (intern name obarray)
547                           value)
548                     plist)))))
549       plist)))
550
551 (defun shr-tag-a (cont)
552   (let ((url (cdr (assq :href cont)))
553         (start (point))
554         shr-start)
555     (shr-generic cont)
556     (shr-urlify (or shr-start start) url)))
557
558 (defun shr-tag-object (cont)
559   (let ((start (point))
560         url)
561     (dolist (elem cont)
562       (when (eq (car elem) 'embed)
563         (setq url (or url (cdr (assq :src (cdr elem))))))
564       (when (and (eq (car elem) 'param)
565                  (equal (cdr (assq :name (cdr elem))) "movie"))
566         (setq url (or url (cdr (assq :value (cdr elem)))))))
567     (when url
568       (shr-insert " [multimedia] ")
569       (shr-urlify start url))
570     (shr-generic cont)))
571
572 (defun shr-tag-video (cont)
573   (let ((image (cdr (assq :poster cont)))
574         (url (cdr (assq :src cont)))
575         (start (point)))
576     (shr-tag-img nil image)
577     (shr-urlify start url)))
578
579 (defun shr-tag-img (cont &optional url)
580   (when (or url
581             (and cont
582                  (cdr (assq :src cont))))
583     (when (and (> (current-column) 0)
584                (not (eq shr-state 'image)))
585       (insert "\n"))
586     (let ((alt (cdr (assq :alt cont)))
587           (url (or url (cdr (assq :src cont)))))
588       (let ((start (point-marker)))
589         (when (zerop (length alt))
590           (setq alt "*"))
591         (cond
592          ((or (member (cdr (assq :height cont)) '("0" "1"))
593               (member (cdr (assq :width cont)) '("0" "1")))
594           ;; Ignore zero-sized or single-pixel images.
595           )
596          ((and (not shr-inhibit-images)
597                (string-match "\\`cid:" url))
598           (let ((url (substring url (match-end 0)))
599                 image)
600             (if (or (not shr-content-function)
601                     (not (setq image (funcall shr-content-function url))))
602                 (insert alt)
603               (shr-put-image image alt))))
604          ((or shr-inhibit-images
605               (and shr-blocked-images
606                    (string-match shr-blocked-images url)))
607           (setq shr-start (point))
608           (let ((shr-state 'space))
609             (if (> (string-width alt) 8)
610                 (shr-insert (truncate-string-to-width alt 8))
611               (shr-insert alt))))
612          ((url-is-cached (shr-encode-url url))
613           (shr-put-image (shr-get-image-data url) alt))
614          (t
615           (insert alt)
616           (ignore-errors
617             (url-retrieve (shr-encode-url url) 'shr-image-fetched
618                           (list (current-buffer) start (point-marker))
619                           t))))
620         (put-text-property start (point) 'keymap shr-map)
621         (put-text-property start (point) 'shr-alt alt)
622         (put-text-property start (point) 'image-url url)
623         (put-text-property start (point) 'image-displayer
624                            (shr-image-displayer shr-content-function))
625         (put-text-property start (point) 'help-echo alt)
626         (setq shr-state 'image)))))
627
628 (defun shr-tag-pre (cont)
629   (let ((shr-folding-mode 'none))
630     (shr-ensure-newline)
631     (shr-indent)
632     (shr-generic cont)
633     (shr-ensure-newline)))
634
635 (defun shr-tag-blockquote (cont)
636   (shr-ensure-paragraph)
637   (shr-indent)
638   (let ((shr-indentation (+ shr-indentation 4)))
639     (shr-generic cont))
640   (shr-ensure-paragraph))
641
642 (defun shr-tag-ul (cont)
643   (shr-ensure-paragraph)
644   (let ((shr-list-mode 'ul))
645     (shr-generic cont))
646   (shr-ensure-paragraph))
647
648 (defun shr-tag-ol (cont)
649   (shr-ensure-paragraph)
650   (let ((shr-list-mode 1))
651     (shr-generic cont))
652   (shr-ensure-paragraph))
653
654 (defun shr-tag-li (cont)
655   (shr-ensure-paragraph)
656   (shr-indent)
657   (let* ((bullet
658           (if (numberp shr-list-mode)
659               (prog1
660                   (format "%d " shr-list-mode)
661                 (setq shr-list-mode (1+ shr-list-mode)))
662             "* "))
663          (shr-indentation (+ shr-indentation (length bullet))))
664     (insert bullet)
665     (shr-generic cont)))
666
667 (defun shr-tag-br (cont)
668   (unless (bobp)
669     (insert "\n")
670     (shr-indent))
671   (shr-generic cont))
672
673 (defun shr-tag-h1 (cont)
674   (shr-heading cont 'bold 'underline))
675
676 (defun shr-tag-h2 (cont)
677   (shr-heading cont 'bold))
678
679 (defun shr-tag-h3 (cont)
680   (shr-heading cont 'italic))
681
682 (defun shr-tag-h4 (cont)
683   (shr-heading cont))
684
685 (defun shr-tag-h5 (cont)
686   (shr-heading cont))
687
688 (defun shr-tag-h6 (cont)
689   (shr-heading cont))
690
691 (defun shr-tag-hr (cont)
692   (shr-ensure-newline)
693   (insert (make-string shr-width shr-hr-line) "\n"))
694
695 ;;; Table rendering algorithm.
696
697 ;; Table rendering is the only complicated thing here.  We do this by
698 ;; first counting how many TDs there are in each TR, and registering
699 ;; how wide they think they should be ("width=45%", etc).  Then we
700 ;; render each TD separately (this is done in temporary buffers, so
701 ;; that we can use all the rendering machinery as if we were in the
702 ;; main buffer).  Now we know how much space each TD really takes, so
703 ;; we then render everything again with the new widths, and finally
704 ;; insert all these boxes into the main buffer.
705 (defun shr-tag-table-1 (cont)
706   (setq cont (or (cdr (assq 'tbody cont))
707                  cont))
708   (let* ((shr-inhibit-images t)
709          (shr-table-depth (1+ shr-table-depth))
710          (shr-kinsoku-shorten t)
711          ;; Find all suggested widths.
712          (columns (shr-column-specs cont))
713          ;; Compute how many characters wide each TD should be.
714          (suggested-widths (shr-pro-rate-columns columns))
715          ;; Do a "test rendering" to see how big each TD is (this can
716          ;; be smaller (if there's little text) or bigger (if there's
717          ;; unbreakable text).
718          (sketch (shr-make-table cont suggested-widths))
719          (sketch-widths (shr-table-widths sketch suggested-widths)))
720     ;; This probably won't work very well.
721     (when (> (+ (loop for width across sketch-widths
722                       summing (1+ width))
723                 shr-indentation 1)
724              (frame-width))
725       (setq truncate-lines t))
726     ;; Then render the table again with these new "hard" widths.
727     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
728   ;; Finally, insert all the images after the table.  The Emacs buffer
729   ;; model isn't strong enough to allow us to put the images actually
730   ;; into the tables.
731   (when (zerop shr-table-depth)
732     (dolist (elem (shr-find-elements cont 'img))
733       (shr-tag-img (cdr elem)))))
734
735 (defun shr-tag-table (cont)
736   (shr-ensure-paragraph)
737   (let* ((caption (cdr (assq 'caption cont)))
738          (header (cdr (assq 'thead cont)))
739          (body (or (cdr (assq 'tbody cont)) cont))
740          (footer (cdr (assq 'tfoot cont)))
741          (nheader (if header (shr-max-columns header)))
742          (nbody (if body (shr-max-columns body)))
743          (nfooter (if footer (shr-max-columns footer))))
744     (shr-tag-table-1
745      (nconc
746       (if caption `((tr (td ,@caption))))
747       (if header
748           (if footer
749               ;; hader + body + footer
750               (if (= nheader nbody)
751                   (if (= nbody nfooter)
752                       `((tr (td (table (tbody ,@header ,@body ,@footer)))))
753                     (nconc `((tr (td (table (tbody ,@header ,@body)))))
754                            (if (= nfooter 1)
755                                footer
756                              `((tr (td (table (tbody ,@footer))))))))
757                 (nconc `((tr (td (table (tbody ,@header)))))
758                        (if (= nbody nfooter)
759                            `((tr (td (table (tbody ,@body ,@footer)))))
760                          (nconc `((tr (td (table (tbody ,@body)))))
761                                 (if (= nfooter 1)
762                                     footer
763                                   `((tr (td (table (tbody ,@footer))))))))))
764             ;; header + body
765             (if (= nheader nbody)
766                 `((tr (td (table (tbody ,@header ,@body)))))
767               (if (= nheader 1)
768                   `(,@header (tr (td (table (tbody ,@body)))))
769                 `((tr (td (table (tbody ,@header))))
770                   (tr (td (table (tbody ,@body))))))))
771         (if footer
772             ;; body + footer
773             (if (= nbody nfooter)
774                 `((tr (td (table (tbody ,@body ,@footer)))))
775               (nconc `((tr (td (table (tbody ,@body)))))
776                      (if (= nfooter 1)
777                          footer
778                        `((tr (td (table (tbody ,@footer))))))))
779           (if caption
780               `((tr (td (table (tbody ,@body)))))
781             body)))))))
782
783 (defun shr-find-elements (cont type)
784   (let (result)
785     (dolist (elem cont)
786       (cond ((eq (car elem) type)
787              (push elem result))
788             ((consp (cdr elem))
789              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
790     (nreverse result)))
791
792 (defun shr-insert-table (table widths)
793   (shr-insert-table-ruler widths)
794   (dolist (row table)
795     (let ((start (point))
796           (height (let ((max 0))
797                     (dolist (column row)
798                       (setq max (max max (cadr column))))
799                     max)))
800       (dotimes (i height)
801         (shr-indent)
802         (insert shr-table-vertical-line "\n"))
803       (dolist (column row)
804         (goto-char start)
805         (let ((lines (nth 2 column))
806               (overlay-lines (nth 3 column))
807               overlay overlay-line)
808           (dolist (line lines)
809             (setq overlay-line (pop overlay-lines))
810             (end-of-line)
811             (insert line shr-table-vertical-line)
812             (dolist (overlay overlay-line)
813               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
814                                      (- (point) (nth 1 overlay) 1)))
815                     (properties (nth 2 overlay)))
816                 (while properties
817                   (overlay-put o (pop properties) (pop properties)))))
818             (forward-line 1))
819           ;; Add blank lines at padding at the bottom of the TD,
820           ;; possibly.
821           (dotimes (i (- height (length lines)))
822             (end-of-line)
823             (insert (make-string (string-width (car lines)) ? )
824                     shr-table-vertical-line)
825             (forward-line 1)))))
826     (shr-insert-table-ruler widths)))
827
828 (defun shr-insert-table-ruler (widths)
829   (when (and (bolp)
830              (> shr-indentation 0))
831     (shr-indent))
832   (insert shr-table-corner)
833   (dotimes (i (length widths))
834     (insert (make-string (aref widths i) shr-table-horizontal-line)
835             shr-table-corner))
836   (insert "\n"))
837
838 (defun shr-table-widths (table suggested-widths)
839   (let* ((length (length suggested-widths))
840          (widths (make-vector length 0))
841          (natural-widths (make-vector length 0)))
842     (dolist (row table)
843       (let ((i 0))
844         (dolist (column row)
845           (aset widths i (max (aref widths i)
846                               (car column)))
847           (aset natural-widths i (max (aref natural-widths i)
848                                       (cadr column)))
849           (setq i (1+ i)))))
850     (let ((extra (- (apply '+ (append suggested-widths nil))
851                     (apply '+ (append widths nil))))
852           (expanded-columns 0))
853       (when (> extra 0)
854         (dotimes (i length)
855           ;; If the natural width is wider than the rendered width, we
856           ;; want to allow the column to expand.
857           (when (> (aref natural-widths i) (aref widths i))
858             (setq expanded-columns (1+ expanded-columns))))
859         (dotimes (i length)
860           (when (> (aref natural-widths i) (aref widths i))
861             (aset widths i (min
862                             (1+ (aref natural-widths i))
863                             (+ (/ extra expanded-columns)
864                                (aref widths i))))))))
865     widths))
866
867 (defun shr-make-table (cont widths &optional fill)
868   (let ((trs nil))
869     (dolist (row cont)
870       (when (eq (car row) 'tr)
871         (let ((tds nil)
872               (columns (cdr row))
873               (i 0)
874               column)
875           (while (< i (length widths))
876             (setq column (pop columns))
877             (when (or (memq (car column) '(td th))
878                       (null column))
879               (push (shr-render-td (cdr column) (aref widths i) fill)
880                     tds)
881               (setq i (1+ i))))
882           (push (nreverse tds) trs))))
883     (nreverse trs)))
884
885 (defun shr-render-td (cont width fill)
886   (with-temp-buffer
887     (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
888       (if cache
889           (insert cache)
890         (let ((shr-width width)
891               (shr-indentation 0))
892           (shr-generic cont))
893         (delete-region
894          (point)
895          (+ (point)
896             (skip-chars-backward " \t\n")))
897         (push (cons (cons width cont) (buffer-string))
898               shr-content-cache)))
899     (goto-char (point-min))
900     (let ((max 0))
901       (while (not (eobp))
902         (end-of-line)
903         (setq max (max max (current-column)))
904         (forward-line 1))
905       (when fill
906         (goto-char (point-min))
907         ;; If the buffer is totally empty, then put a single blank
908         ;; line here.
909         (if (zerop (buffer-size))
910             (insert (make-string width ? ))
911           ;; Otherwise, fill the buffer.
912           (while (not (eobp))
913             (end-of-line)
914             (when (> (- width (current-column)) 0)
915               (insert (make-string (- width (current-column)) ? )))
916             (forward-line 1))))
917       (if fill
918           (list max
919                 (count-lines (point-min) (point-max))
920                 (split-string (buffer-string) "\n")
921                 (shr-collect-overlays))
922         (list max
923               (shr-natural-width))))))
924
925 (defun shr-natural-width ()
926   (goto-char (point-min))
927   (let ((current 0)
928         (max 0))
929     (while (not (eobp))
930       (end-of-line)
931       (setq current (+ current (current-column)))
932       (unless (get-text-property (point) 'shr-break)
933         (setq max (max max current)
934               current 0))
935       (forward-line 1))
936     max))
937
938 (defun shr-collect-overlays ()
939   (save-excursion
940     (goto-char (point-min))
941     (let ((overlays nil))
942       (while (not (eobp))
943         (push (shr-overlays-in-region (point) (line-end-position))
944               overlays)
945         (forward-line 1))
946       (nreverse overlays))))
947
948 (defun shr-overlays-in-region (start end)
949   (let (result)
950     (dolist (overlay (overlays-in start end))
951       (push (list (if (> start (overlay-start overlay))
952                       (- end start)
953                     (- end (overlay-start overlay)))
954                   (if (< end (overlay-end overlay))
955                       0
956                     (- end (overlay-end overlay)))
957                   (overlay-properties overlay))
958             result))
959     (nreverse result)))
960
961 (defun shr-pro-rate-columns (columns)
962   (let ((total-percentage 0)
963         (widths (make-vector (length columns) 0)))
964     (dotimes (i (length columns))
965       (setq total-percentage (+ total-percentage (aref columns i))))
966     (setq total-percentage (/ 1.0 total-percentage))
967     (dotimes (i (length columns))
968       (aset widths i (max (truncate (* (aref columns i)
969                                        total-percentage
970                                        (- shr-width (1+ (length columns)))))
971                           10)))
972     widths))
973
974 ;; Return a summary of the number and shape of the TDs in the table.
975 (defun shr-column-specs (cont)
976   (let ((columns (make-vector (shr-max-columns cont) 1)))
977     (dolist (row cont)
978       (when (eq (car row) 'tr)
979         (let ((i 0))
980           (dolist (column (cdr row))
981             (when (memq (car column) '(td th))
982               (let ((width (cdr (assq :width (cdr column)))))
983                 (when (and width
984                            (string-match "\\([0-9]+\\)%" width))
985                   (aset columns i
986                         (/ (string-to-number (match-string 1 width))
987                            100.0))))
988               (setq i (1+ i)))))))
989     columns))
990
991 (defun shr-count (cont elem)
992   (let ((i 0))
993     (dolist (sub cont)
994       (when (eq (car sub) elem)
995         (setq i (1+ i))))
996     i))
997
998 (defun shr-max-columns (cont)
999   (let ((max 0))
1000     (dolist (row cont)
1001       (when (eq (car row) 'tr)
1002         (setq max (max max (+ (shr-count (cdr row) 'td)
1003                               (shr-count (cdr row) 'th))))))
1004     max))
1005
1006 (provide 'shr)
1007
1008 ;;; shr.el ends here