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