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