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