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