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