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