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