60fa1271939753455d6b945b9d8cc22bed3b419d
[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 (autoload 'shr-color-visible "shr-color")
521 (defun shr-tag-color-check (fg &optional bg)
522   "Check that FG is visible on BG."
523   (shr-color-visible (or (shr-color->hexadecimal bg)
524                          (frame-parameter nil 'background-color))
525                      (shr-color->hexadecimal fg) (not bg)))
526
527 (defun shr-tag-insert-color-overlay (color start end)
528   (when color
529     (let ((overlay (make-overlay start end)))
530       (overlay-put overlay 'face (cons 'foreground-color
531                                        (cadr (shr-tag-color-check color)))))))
532
533 (defun shr-tag-span (cont)
534   (let ((start (point))
535         (color (cdr (assq 'color (shr-parse-style (cdr (assq :style cont)))))))
536     (shr-generic cont)
537     (shr-tag-insert-color-overlay color start (point))))
538
539 (defun shr-tag-font (cont)
540   (let ((start (point))
541         (color (cdr (assq :color cont))))
542     (shr-generic cont)
543     (shr-tag-insert-color-overlay color start (point))))
544
545 (defun shr-parse-style (style)
546   (when style
547     (let ((plist nil))
548       (dolist (elem (split-string style ";"))
549         (when elem
550           (setq elem (split-string elem ":"))
551           (when (and (car elem)
552                      (cadr elem))
553             (let ((name (replace-regexp-in-string "^ +\\| +$" "" (car elem)))
554                   (value (replace-regexp-in-string "^ +\\| +$" "" (cadr elem))))
555               (push (cons (intern name obarray)
556                           value)
557                     plist)))))
558       plist)))
559
560 (defun shr-tag-a (cont)
561   (let ((url (cdr (assq :href cont)))
562         (start (point))
563         shr-start)
564     (shr-generic cont)
565     (shr-urlify (or shr-start start) url)))
566
567 (defun shr-tag-object (cont)
568   (let ((start (point))
569         url)
570     (dolist (elem cont)
571       (when (eq (car elem) 'embed)
572         (setq url (or url (cdr (assq :src (cdr elem))))))
573       (when (and (eq (car elem) 'param)
574                  (equal (cdr (assq :name (cdr elem))) "movie"))
575         (setq url (or url (cdr (assq :value (cdr elem)))))))
576     (when url
577       (shr-insert " [multimedia] ")
578       (shr-urlify start url))
579     (shr-generic cont)))
580
581 (defun shr-tag-video (cont)
582   (let ((image (cdr (assq :poster cont)))
583         (url (cdr (assq :src cont)))
584         (start (point)))
585     (shr-tag-img nil image)
586     (shr-urlify start url)))
587
588 (defun shr-tag-img (cont &optional url)
589   (when (or url
590             (and cont
591                  (cdr (assq :src cont))))
592     (when (and (> (current-column) 0)
593                (not (eq shr-state 'image)))
594       (insert "\n"))
595     (let ((alt (cdr (assq :alt cont)))
596           (url (or url (cdr (assq :src cont)))))
597       (let ((start (point-marker)))
598         (when (zerop (length alt))
599           (setq alt "*"))
600         (cond
601          ((or (member (cdr (assq :height cont)) '("0" "1"))
602               (member (cdr (assq :width cont)) '("0" "1")))
603           ;; Ignore zero-sized or single-pixel images.
604           )
605          ((and (not shr-inhibit-images)
606                (string-match "\\`cid:" url))
607           (let ((url (substring url (match-end 0)))
608                 image)
609             (if (or (not shr-content-function)
610                     (not (setq image (funcall shr-content-function url))))
611                 (insert alt)
612               (shr-put-image image alt))))
613          ((or shr-inhibit-images
614               (and shr-blocked-images
615                    (string-match shr-blocked-images url)))
616           (setq shr-start (point))
617           (let ((shr-state 'space))
618             (if (> (string-width alt) 8)
619                 (shr-insert (truncate-string-to-width alt 8))
620               (shr-insert alt))))
621          ((url-is-cached (shr-encode-url url))
622           (shr-put-image (shr-get-image-data url) alt))
623          (t
624           (insert alt)
625           (ignore-errors
626             (url-retrieve (shr-encode-url url) 'shr-image-fetched
627                           (list (current-buffer) start (point-marker))
628                           t))))
629         (put-text-property start (point) 'keymap shr-map)
630         (put-text-property start (point) 'shr-alt alt)
631         (put-text-property start (point) 'image-url url)
632         (put-text-property start (point) 'image-displayer
633                            (shr-image-displayer shr-content-function))
634         (put-text-property start (point) 'help-echo alt)
635         (setq shr-state 'image)))))
636
637 (defun shr-tag-pre (cont)
638   (let ((shr-folding-mode 'none))
639     (shr-ensure-newline)
640     (shr-indent)
641     (shr-generic cont)
642     (shr-ensure-newline)))
643
644 (defun shr-tag-blockquote (cont)
645   (shr-ensure-paragraph)
646   (shr-indent)
647   (let ((shr-indentation (+ shr-indentation 4)))
648     (shr-generic cont))
649   (shr-ensure-paragraph))
650
651 (defun shr-tag-ul (cont)
652   (shr-ensure-paragraph)
653   (let ((shr-list-mode 'ul))
654     (shr-generic cont))
655   (shr-ensure-paragraph))
656
657 (defun shr-tag-ol (cont)
658   (shr-ensure-paragraph)
659   (let ((shr-list-mode 1))
660     (shr-generic cont))
661   (shr-ensure-paragraph))
662
663 (defun shr-tag-li (cont)
664   (shr-ensure-paragraph)
665   (shr-indent)
666   (let* ((bullet
667           (if (numberp shr-list-mode)
668               (prog1
669                   (format "%d " shr-list-mode)
670                 (setq shr-list-mode (1+ shr-list-mode)))
671             "* "))
672          (shr-indentation (+ shr-indentation (length bullet))))
673     (insert bullet)
674     (shr-generic cont)))
675
676 (defun shr-tag-br (cont)
677   (unless (bobp)
678     (insert "\n")
679     (shr-indent))
680   (shr-generic cont))
681
682 (defun shr-tag-h1 (cont)
683   (shr-heading cont 'bold 'underline))
684
685 (defun shr-tag-h2 (cont)
686   (shr-heading cont 'bold))
687
688 (defun shr-tag-h3 (cont)
689   (shr-heading cont 'italic))
690
691 (defun shr-tag-h4 (cont)
692   (shr-heading cont))
693
694 (defun shr-tag-h5 (cont)
695   (shr-heading cont))
696
697 (defun shr-tag-h6 (cont)
698   (shr-heading cont))
699
700 (defun shr-tag-hr (cont)
701   (shr-ensure-newline)
702   (insert (make-string shr-width shr-hr-line) "\n"))
703
704 ;;; Table rendering algorithm.
705
706 ;; Table rendering is the only complicated thing here.  We do this by
707 ;; first counting how many TDs there are in each TR, and registering
708 ;; how wide they think they should be ("width=45%", etc).  Then we
709 ;; render each TD separately (this is done in temporary buffers, so
710 ;; that we can use all the rendering machinery as if we were in the
711 ;; main buffer).  Now we know how much space each TD really takes, so
712 ;; we then render everything again with the new widths, and finally
713 ;; insert all these boxes into the main buffer.
714 (defun shr-tag-table-1 (cont)
715   (setq cont (or (cdr (assq 'tbody cont))
716                  cont))
717   (let* ((shr-inhibit-images t)
718          (shr-table-depth (1+ shr-table-depth))
719          (shr-kinsoku-shorten t)
720          ;; Find all suggested widths.
721          (columns (shr-column-specs cont))
722          ;; Compute how many characters wide each TD should be.
723          (suggested-widths (shr-pro-rate-columns columns))
724          ;; Do a "test rendering" to see how big each TD is (this can
725          ;; be smaller (if there's little text) or bigger (if there's
726          ;; unbreakable text).
727          (sketch (shr-make-table cont suggested-widths))
728          (sketch-widths (shr-table-widths sketch suggested-widths)))
729     ;; This probably won't work very well.
730     (when (> (+ (loop for width across sketch-widths
731                       summing (1+ width))
732                 shr-indentation 1)
733              (frame-width))
734       (setq truncate-lines t))
735     ;; Then render the table again with these new "hard" widths.
736     (shr-insert-table (shr-make-table cont sketch-widths t) sketch-widths))
737   ;; Finally, insert all the images after the table.  The Emacs buffer
738   ;; model isn't strong enough to allow us to put the images actually
739   ;; into the tables.
740   (when (zerop shr-table-depth)
741     (dolist (elem (shr-find-elements cont 'img))
742       (shr-tag-img (cdr elem)))))
743
744 (defun shr-tag-table (cont)
745   (shr-ensure-paragraph)
746   (let* ((caption (cdr (assq 'caption cont)))
747          (header (cdr (assq 'thead cont)))
748          (body (or (cdr (assq 'tbody cont)) cont))
749          (footer (cdr (assq 'tfoot cont)))
750          (nheader (if header (shr-max-columns header)))
751          (nbody (if body (shr-max-columns body)))
752          (nfooter (if footer (shr-max-columns footer))))
753     (shr-tag-table-1
754      (nconc
755       (if caption `((tr (td ,@caption))))
756       (if header
757           (if footer
758               ;; hader + body + footer
759               (if (= nheader nbody)
760                   (if (= nbody nfooter)
761                       `((tr (td (table (tbody ,@header ,@body ,@footer)))))
762                     (nconc `((tr (td (table (tbody ,@header ,@body)))))
763                            (if (= nfooter 1)
764                                footer
765                              `((tr (td (table (tbody ,@footer))))))))
766                 (nconc `((tr (td (table (tbody ,@header)))))
767                        (if (= nbody nfooter)
768                            `((tr (td (table (tbody ,@body ,@footer)))))
769                          (nconc `((tr (td (table (tbody ,@body)))))
770                                 (if (= nfooter 1)
771                                     footer
772                                   `((tr (td (table (tbody ,@footer))))))))))
773             ;; header + body
774             (if (= nheader nbody)
775                 `((tr (td (table (tbody ,@header ,@body)))))
776               (if (= nheader 1)
777                   `(,@header (tr (td (table (tbody ,@body)))))
778                 `((tr (td (table (tbody ,@header))))
779                   (tr (td (table (tbody ,@body))))))))
780         (if footer
781             ;; body + footer
782             (if (= nbody nfooter)
783                 `((tr (td (table (tbody ,@body ,@footer)))))
784               (nconc `((tr (td (table (tbody ,@body)))))
785                      (if (= nfooter 1)
786                          footer
787                        `((tr (td (table (tbody ,@footer))))))))
788           (if caption
789               `((tr (td (table (tbody ,@body)))))
790             body)))))))
791
792 (defun shr-find-elements (cont type)
793   (let (result)
794     (dolist (elem cont)
795       (cond ((eq (car elem) type)
796              (push elem result))
797             ((consp (cdr elem))
798              (setq result (nconc (shr-find-elements (cdr elem) type) result)))))
799     (nreverse result)))
800
801 (defun shr-insert-table (table widths)
802   (shr-insert-table-ruler widths)
803   (dolist (row table)
804     (let ((start (point))
805           (height (let ((max 0))
806                     (dolist (column row)
807                       (setq max (max max (cadr column))))
808                     max)))
809       (dotimes (i height)
810         (shr-indent)
811         (insert shr-table-vertical-line "\n"))
812       (dolist (column row)
813         (goto-char start)
814         (let ((lines (nth 2 column))
815               (overlay-lines (nth 3 column))
816               overlay overlay-line)
817           (dolist (line lines)
818             (setq overlay-line (pop overlay-lines))
819             (end-of-line)
820             (insert line shr-table-vertical-line)
821             (dolist (overlay overlay-line)
822               (let ((o (make-overlay (- (point) (nth 0 overlay) 1)
823                                      (- (point) (nth 1 overlay) 1)))
824                     (properties (nth 2 overlay)))
825                 (while properties
826                   (overlay-put o (pop properties) (pop properties)))))
827             (forward-line 1))
828           ;; Add blank lines at padding at the bottom of the TD,
829           ;; possibly.
830           (dotimes (i (- height (length lines)))
831             (end-of-line)
832             (insert (make-string (string-width (car lines)) ? )
833                     shr-table-vertical-line)
834             (forward-line 1)))))
835     (shr-insert-table-ruler widths)))
836
837 (defun shr-insert-table-ruler (widths)
838   (when (and (bolp)
839              (> shr-indentation 0))
840     (shr-indent))
841   (insert shr-table-corner)
842   (dotimes (i (length widths))
843     (insert (make-string (aref widths i) shr-table-horizontal-line)
844             shr-table-corner))
845   (insert "\n"))
846
847 (defun shr-table-widths (table suggested-widths)
848   (let* ((length (length suggested-widths))
849          (widths (make-vector length 0))
850          (natural-widths (make-vector length 0)))
851     (dolist (row table)
852       (let ((i 0))
853         (dolist (column row)
854           (aset widths i (max (aref widths i)
855                               (car column)))
856           (aset natural-widths i (max (aref natural-widths i)
857                                       (cadr column)))
858           (setq i (1+ i)))))
859     (let ((extra (- (apply '+ (append suggested-widths nil))
860                     (apply '+ (append widths nil))))
861           (expanded-columns 0))
862       (when (> extra 0)
863         (dotimes (i length)
864           ;; If the natural width is wider than the rendered width, we
865           ;; want to allow the column to expand.
866           (when (> (aref natural-widths i) (aref widths i))
867             (setq expanded-columns (1+ expanded-columns))))
868         (dotimes (i length)
869           (when (> (aref natural-widths i) (aref widths i))
870             (aset widths i (min
871                             (1+ (aref natural-widths i))
872                             (+ (/ extra expanded-columns)
873                                (aref widths i))))))))
874     widths))
875
876 (defun shr-make-table (cont widths &optional fill)
877   (let ((trs nil))
878     (dolist (row cont)
879       (when (eq (car row) 'tr)
880         (let ((tds nil)
881               (columns (cdr row))
882               (i 0)
883               column)
884           (while (< i (length widths))
885             (setq column (pop columns))
886             (when (or (memq (car column) '(td th))
887                       (null column))
888               (push (shr-render-td (cdr column) (aref widths i) fill)
889                     tds)
890               (setq i (1+ i))))
891           (push (nreverse tds) trs))))
892     (nreverse trs)))
893
894 (defun shr-render-td (cont width fill)
895   (with-temp-buffer
896     (let ((cache (cdr (assoc (cons width cont) shr-content-cache))))
897       (if cache
898           (insert cache)
899         (let ((shr-width width)
900               (shr-indentation 0))
901           (shr-generic cont))
902         (delete-region
903          (point)
904          (+ (point)
905             (skip-chars-backward " \t\n")))
906         (push (cons (cons width cont) (buffer-string))
907               shr-content-cache)))
908     (goto-char (point-min))
909     (let ((max 0))
910       (while (not (eobp))
911         (end-of-line)
912         (setq max (max max (current-column)))
913         (forward-line 1))
914       (when fill
915         (goto-char (point-min))
916         ;; If the buffer is totally empty, then put a single blank
917         ;; line here.
918         (if (zerop (buffer-size))
919             (insert (make-string width ? ))
920           ;; Otherwise, fill the buffer.
921           (while (not (eobp))
922             (end-of-line)
923             (when (> (- width (current-column)) 0)
924               (insert (make-string (- width (current-column)) ? )))
925             (forward-line 1))))
926       (if fill
927           (list max
928                 (count-lines (point-min) (point-max))
929                 (split-string (buffer-string) "\n")
930                 (shr-collect-overlays))
931         (list max
932               (shr-natural-width))))))
933
934 (defun shr-natural-width ()
935   (goto-char (point-min))
936   (let ((current 0)
937         (max 0))
938     (while (not (eobp))
939       (end-of-line)
940       (setq current (+ current (current-column)))
941       (unless (get-text-property (point) 'shr-break)
942         (setq max (max max current)
943               current 0))
944       (forward-line 1))
945     max))
946
947 (defun shr-collect-overlays ()
948   (save-excursion
949     (goto-char (point-min))
950     (let ((overlays nil))
951       (while (not (eobp))
952         (push (shr-overlays-in-region (point) (line-end-position))
953               overlays)
954         (forward-line 1))
955       (nreverse overlays))))
956
957 (defun shr-overlays-in-region (start end)
958   (let (result)
959     (dolist (overlay (overlays-in start end))
960       (push (list (if (> start (overlay-start overlay))
961                       (- end start)
962                     (- end (overlay-start overlay)))
963                   (if (< end (overlay-end overlay))
964                       0
965                     (- end (overlay-end overlay)))
966                   (overlay-properties overlay))
967             result))
968     (nreverse result)))
969
970 (defun shr-pro-rate-columns (columns)
971   (let ((total-percentage 0)
972         (widths (make-vector (length columns) 0)))
973     (dotimes (i (length columns))
974       (setq total-percentage (+ total-percentage (aref columns i))))
975     (setq total-percentage (/ 1.0 total-percentage))
976     (dotimes (i (length columns))
977       (aset widths i (max (truncate (* (aref columns i)
978                                        total-percentage
979                                        (- shr-width (1+ (length columns)))))
980                           10)))
981     widths))
982
983 ;; Return a summary of the number and shape of the TDs in the table.
984 (defun shr-column-specs (cont)
985   (let ((columns (make-vector (shr-max-columns cont) 1)))
986     (dolist (row cont)
987       (when (eq (car row) 'tr)
988         (let ((i 0))
989           (dolist (column (cdr row))
990             (when (memq (car column) '(td th))
991               (let ((width (cdr (assq :width (cdr column)))))
992                 (when (and width
993                            (string-match "\\([0-9]+\\)%" width))
994                   (aset columns i
995                         (/ (string-to-number (match-string 1 width))
996                            100.0))))
997               (setq i (1+ i)))))))
998     columns))
999
1000 (defun shr-count (cont elem)
1001   (let ((i 0))
1002     (dolist (sub cont)
1003       (when (eq (car sub) elem)
1004         (setq i (1+ i))))
1005     i))
1006
1007 (defun shr-max-columns (cont)
1008   (let ((max 0))
1009     (dolist (row cont)
1010       (when (eq (car row) 'tr)
1011         (setq max (max max (+ (shr-count (cdr row) 'td)
1012                               (shr-count (cdr row) 'th))))))
1013     max))
1014
1015 (provide 'shr)
1016
1017 ;;; shr.el ends here