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