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